修改这段代码,使其能够顺利运行:#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main(){ pid_t pc1,pc2,pw1,pw2; pc1=fork(); pc2=fork(); if (pc1>0&&pc2>0) { //*父进程 pw1=wait(NULL); pw2=wait(NULL); printf("***Catch a dead child process with pid: %d\n",pw1); printf("***Catch a dead child process with pid: %d\n",pw2); printf("***I'M %d,THE MAIN PROCESS LEAVE!\n",getpid()); }//if if (pc1==0&&pc2>0) { //*子进程1 printf("===I'M the first child PID:%d,my father is:%d\n",getpid(),getppid()); sleep(10); }//if if (pc1>0&&pc2==0) //*子进程2 printf("===I'M the 2nd child PID:%d,my father is:%d,i don't sleep.\n",getpid(),getppid()); if (pc1==0&&pc2==0) //*孙进程 printf("I'M grandson PID:%d,my father is:%d,no one is waiting for – me.\n",getpid(),getppid()); exit(0); } //main
时间: 2024-01-23 08:02:04 浏览: 76
这段代码存在一些问题,需要进行修改:
1. 在第一个子进程执行pc2=fork()之前需要加上exit(0),否则会产生多余的孙进程。
2. 在if (pc1>0&&pc2>0)的代码块中需要加上else,否则会执行多次输出的操作。
修改后的代码如下:
```
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
pid_t pc1,pc2,pw1,pw2;
pc1=fork();
if (pc1 == 0) {
//*子进程1
printf("===I'M the first child PID:%d,my father is:%d\n",getpid(),getppid());
exit(0);
} else if (pc1 > 0) {
pc2=fork();
if (pc2 == 0) {
//*子进程2
printf("===I'M the 2nd child PID:%d,my father is:%d,i don't sleep.\n",getpid(),getppid());
exit(0);
} else if (pc2 > 0) {
//*父进程
pw1=wait(NULL);
pw2=wait(NULL);
printf("***Catch a dead child process with pid: %d\n",pw1);
printf("***Catch a dead child process with pid: %d\n",pw2);
printf("***I'M %d,THE MAIN PROCESS LEAVE!\n",getpid());
}
}
return 0;
}
```
阅读全文