【发布时间】:2015-11-06 17:16:53
【问题描述】:
我正在尝试编写一个小程序,从单亲派生进程。目前我的代码执行了几次,但随后孩子们创建了更多的子进程,我想消除这些。
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 只是从父级分叉。
编辑:感谢您的帮助,得到了解决方案:
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);
}
}
}
【问题讨论】:
-
1) 变量“n”应该是什么?它没有定义。建议使用“pid_t”变量中的值。 2)问题是关于运行时问题,但发布的代码无法编译。请贴出真实代码。
标签: c process fork parent-child