【发布时间】:2018-02-11 15:46:51
【问题描述】:
我目前正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息。第一个是“我是父母”,第二个是“父母已经完成”。子进程“I am the child”和“The child 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());
}
【问题讨论】:
-
pthreads 与问题有何关系?如果没有,请删除标签并在问题中提及它。
标签: c fork parent-child