我在尝试解决这个问题时遇到了很大的痛苦。因此,我想做的是创建 3 个源自一个父进程的子进程。我已经弄清楚了,但问题是我的程序在到达第三个 child 时退出,使其成为孤儿(我认为)。这是我的第一代进程的代码:
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
最佳答案
如果我能猜对的话,你担心子进程会成为孤儿进程,那么你可以使用wait或waitpid。通过使用其中任何一个,父进程可以等待子进程终止。 如需更多帮助,请使用“man wait”。
关于c - 涉及for循环的fork函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075216/