【发布时间】:2015-10-12 22:40:19
【问题描述】:
我正在使用 Eclipse Luna IDE 在 Debian 发行版下使用 C 语言进行编程。
我的程序的主进程应该只执行一次,因此只创建3个子进程,然后在所有子进程结束后结束。
我看不出我的代码有什么问题,但我的程序创建了超过 3 个不同父亲的孩子。
有人可以告诉我如何获得预期的输出吗?
似乎主函数执行不止一次,但它没有循环来执行它。
这是我的代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main(){
pid_t IMU1_PID, IMU2_PID, IMU3_PID;
IMU1_PID=fork();
IMU2_PID=fork();
IMU3_PID=fork();
if (IMU1_PID<0 || IMU2_PID<0 || IMU3_PID<0) { perror("fork"); exit(errno);}
if(IMU1_PID==0){
printf("child1's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}
if(IMU2_PID==0){
printf("child2's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}
if(IMU3_PID==0){
printf("child3's PID: %d - father's PID: %d\n",getpid(),getppid());
sleep(2);
exit(0);
}
printf("PARENT %d waiting until all CHILDS end\n",getpid());
while(wait(NULL)!=-1);
printf("PARENT %d after all CHILDS ended\n",getpid());
return 0;
}
这里是输出:
PARENT 4282 waiting until all CHILDS end
child3's PID: 4285 - father's PID: 4282
child2's PID: 4284 - father's PID: 4282
child2's PID: 4286 - father's PID: 4284
child1's PID: 4288 - father's PID: 4283
child1's PID: 4283 - father's PID: 4282
child1's PID: 4287 - father's PID: 4283
child1's PID: 4289 - father's PID: 4287
PARENT 4282 after all CHILDS ended
这是我所期望的:
PARENT 4282 waiting until all CHILDS end
child3's PID: 4285 - father's PID: 4282
child2's PID: 4284 - father's PID: 4282
child1's PID: 4288 - father's PID: 4282
PARENT 4282 after all CHILDS ended
【问题讨论】:
-
为什么你认为“我的程序的主进程应该只执行一次......”?根据定义,当您 fork 时,
fork()的函数的其余部分(在本例中为main)在原始进程和新创建的进程中都执行。 -
谢谢!起初我无法理解你,但现在我明白了。
标签: c multithreading concurrency fork