Parent/Child 处理打印

Parent/Child process print

我正在编写一个创建 child 进程的 C 程序。创建 child 进程后,parent 进程应该输出两条消息:"I am the parent" 然后它应该打印 "The parent is done"。 child 进程 "I am child" 和 "The child is done" 相同。但是我想确保 child 的第二条消息总是在 parent 的第二条消息之前完成。我怎样才能打印 "The child is done" 和 "The parent is done" 而不是打印它们的 pid?

#include <unistd.h>
#include <stdio.h>

main()
{
  int pid, stat_loc;


  printf("\nmy pid = %d\n", getpid());
  pid = fork();

  if (pid == -1)
    perror("error in fork");

  else if (pid ==0 )
    { 
       printf("\nI am the child process, my pid = %d\n\n", getpid());


    } 
  else  
    {
      printf("\nI am the parent process, my pid = %d\n\n", getpid());       
      sleep(2);
    }  
  printf("\nThe %d is done\n\n", getpid());
}

在父进程中调用wait(2)让子进程完成。

  else
    {
      wait(0);
      printf("\nI am the parent process, my pid = %d\n\n", getpid());
    }

您应该检查 wait() 是否成功并且 main() 的 return 类型应该是 int.

您可以有一个标志变量,它在父项中设置,但随后子项将其清除。然后简单地检查最后一个输出。

类似

int is_parent = 1;  // Important to create and initialize before the fork

pid = fork();

if (pid == -1) { ... }

if (pid == 0)
{
    printf("\nI am the child process, my pid = %d\n\n", getpid());
    in_parent = 0;  // We're not in the parent anymore
}
else { ... }

printf("\nThe %s is done\n\n", is_parent ? "parent" : child");