我试图解决这个问题时遇到了很多痛苦。所以,我要做的是创建源于一个父进程的3个子进程。我已经想到了,但问题是我的程序退出时,它到达第三个孩子让它成为孤儿(我想)。这是第一代流程的代码:
int i = 0;
int corpse;
int status;
pid_t child;
about("Dad");
printf("Now .. Forking !!\n");
about("Dad");
for(i=0; i<3; i++){
child = fork();
if (child == 0){
about ("son");
break;
}else if (child < 0){
perror ("Unable to fork!");
break;
}
}
void about(char * msg)
{
pid_t me;
pid_t old;
me = getpid();
old = getppid();
printf("[%s] Hi, my pid is %d and I come from %d.\n", msg, me, old);
}
while ((corpse = wait(&status)) > 0){
printf("Child process PID=%d terminates\n", corpse);
}
现在我的输出如下:
[Dad] Hi, my pid is 2940 and I come from 2883.
Now .. Forking !!
[Dad] Hi, my pid is 2940 and I come from 2883.
[son] Hi, my pid is 2941 and I come from 2940.
[son] Hi, my pid is 2942 and I come from 2940.
Child process PID=2941 terminates
Child process PID=2942 terminates
[son] Hi, my pid is 2943 and I come from 2940.
Child process PID=2943 terminates
答案 0 :(得分:1)
如果我能做对,你担心孩子过程变成孤儿,那么你可以使用等待或等待。通过使用其中任何一个,父进程可以等待子进程终止。 如需更多帮助,请使用“man wait”。