父/子进程打印

时间:2016-01-31 16:56:17

标签: c multithreading pthreads fork

我正在编写一个创建子进程的C程序。创建子进程后,父进程应该输出两条消息:"我是父进程"然后它应该打印"父母完成"。同样适用于儿童流程"我是孩子"和#34;孩子已经完成了#34;。但是我想确保,孩子的第二条消息总是在父母的第二条消息之前完成。如何实现打印"孩子已完成"并且"父母完成了#34;而不是打印他们的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());
}

2 个答案:

答案 0 :(得分:1)

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

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

您应该检查wait()是否成功,main()的返回类型应该是int

答案 1 :(得分:1)

你可以有一个在父级中设置的标志变量,但是孩子会清除它。然后只需检查最后一次输出。

这样的东西
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");