我在使用fork
函数时遇到问题。我想编写一个程序,C程序子进程在父进程之前再次擦除
- 派生四个过程
- 打印每个进程的PID,地重复印刷的PID
- 打印父母的PID
但是,当最后一个子进程结束我不能跳回到第一个子进程,只打印最后一个孩子的PID。如何在父进程之前再次运行子进程?
int noOfPlayer=4;
int pid,myid,status,grandchild;
int i=0;
int a=1;
int x=1;
myid = getpid();
for(i=0;i<noOfPlayer;i++){
pid=fork();
if(pid<0){ //error occurred
printf("Fork Failed\n");exit(1);
} else if (pid==0) {//child process
myid=getpid();
printf("Child %d, pid %d\n",i+1,myid);
printf("ABC Child %d, pid %d\n",i+1,myid);
exit(0);
} else { //parent process
wait(NULL);
}
}
printf("I am parent, pid %d: all children finished\n", myid);
结果是
儿童1,PID 21989
ABC儿童1,PID 21989
儿童2,PID 21990
ABC儿童2,PID 21990
儿童3,PID 21991
ABC孩子3,孩子21991
孩子4,孩子21992
孩子4,孩子21992
我的父母,PID 21988:所有的孩子完成
但我想
儿童1,PID 21989
儿童2,PID 21990
儿童3,PID 21991
儿童4,PID 21992
ABC子1,PID 21989
ABC子2,PID 21990
ABC子3,PID 21991
ABC子4,PID 21992
对我不太清楚。你有一些代码给我们看? –
“跳回第一个孩子的过程”是什么意思? – Downvoter
您的输出是可预测的,因为您一次只运行一个子进程(父进程等待每个进程退出)。无论如何,你可能想在循环外面“wait()”。这仍然可能不会给你你期望的输出(因为孩子之间没有订单保证,并且标准输出可能被缓冲) – Hasturkun