【发布时间】:2020-04-27 19:10:33
【问题描述】:
我有一个任务,它让我将此代码转换为使父进程等待所有子进程完成的代码。 PS:第一个代码有4个进程,需要使用waitpid来解决。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t p = fork();
pid_t k = fork();
if(p>0){
printf("p=%d: PID = %d\n", p, getpid());
sleep(45);
exit(0);
}
else if(p==0){
printf("p=%d: PID = %d\n", p, getpid());
exit(0);
}
else if(p<0){
printf("ERRO! p=%d\n", p);
exit(p);
}
}
我已经尝试过了,但我认为这仅适用于 1 个子进程,而不适用于其中很多。
int main(){
pid_t p = fork();
pid_t k = fork();
if(p<0){
printf("fodeu");
exit(p);
}
else if(p==0){
printf("");
exit(0);
}
else{
for(i=0;i<4;i++){
int returnstatus;
waitpid(p,&returnstatus,0);
if(returnstatus == 0){
printf("o processo filho correu normalmente");
}
else if(returnstatus == 1){
printf("o processo filho ardeu");
}
}
}
}
【问题讨论】:
-
其实这只是你的问题之一。另一个是你忽略了
k。 -
你从不使用
k,第二个fork()的返回值。您需要p > 0和k > 0来识别原始进程,该进程必须完成大部分等待(它有两个孩子)。您原来的子进程也必须等待。最简单的方法是让每个进程等待它没有子进程——一个调用wait()或waitpid()并报告退出状态的while 循环。没有子进程的进程将立即退出循环并终止,允许其父进程继续。请注意,您的原始进程没有 4 个子进程; for 循环不合适。 -
不要忘记在语句末尾打印一个换行符。如果您正在处理多个进程,最好将进程报告的 PID 包含在来自
printf()的输出中。