【发布时间】:2016-05-09 01:50:19
【问题描述】:
我正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息:“我是父进程”,然后它应该打印“父进程完成”。子进程“我是孩子”和“孩子完成了”也是如此。但是我想确保,孩子的第二条消息总是在父母的第二条消息之前完成。我怎样才能实现打印“孩子完成”和“父母完成”而不是打印他们的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());
}
【问题讨论】:
标签: c multithreading pthreads fork