我正在尝试编写一个小程序,从单个父进程中 fork 进程。目前,我的代码执行了几次此操作,但随后子进程创建了更多子进程,我想消除这些子进程。
int main() {
pid_t c;
for (int i = 0; i < 5; i++) {
c = fork();
if(c < 0) {
perror("fork");
exit(1);
}
else if( c > 0 ) {
printf("parentID = %d, childID = %d\n", getppid(i), getpid(i));
}
}
}
我不知道如何修改它,以便 fork 仅从父级 fork 。
编辑:感谢您的帮助,找到解决方案:
int main() {
pid_t c;
for (int i = 0; i < 5; i++) {
c = fork();
if(c < 0) {
perror("fork");
exit(1);
}
else if( c > 0 ) {
printf("parentID = %d, childID = %d\n", getppid(i), getpid(i));
}
else {
exit(0);
}
}
}
最佳答案
发布的代码中没有任何内容可以识别子进程(0 == pid)
因此, child 会点击(并跳过)两个“if”语句。
到达循环末尾,
分支回到循环顶部,调用 fork().... 等。
建议:添加
elseif( 0 == pid )
{ // then child ...
exit( EXIT_SUCCESS );
}
关于C - 从单亲 fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572143/