我正在编写一个创建子进程的 C 程序。创建子进程后,父进程应该输出两条消息:“I am the parent”然后它应该打印“The parent is done”。对于子进程“我是 child ”和“ child 已经完成”也是如此。但是我想确保, child 的第二条消息总是在 parent 的第二条消息之前完成。我怎样才能打印“ child 完成”和“ parent 完成”而不是打印他们的 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());
}
最佳答案
您可以有一个标志变量,它在父级中设置,但随后子级将其清除。然后简单地检查最后的输出。
有点像
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");
关于c - 父子进程打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116512/