【发布时间】:2019-05-16 16:02:43
【问题描述】:
每个printf 命令代表一个进程。 p0 进程应等待 p2 进程执行,而 p2 应等待至少 2 个子进程 (p3,p4,p5) 先执行:
```
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#define _POSIX_SOURCE
int main()
{
int pid1, pid2, pid3, pid4, pid5;
int i;
int status;
pid1=fork();
if (pid1 != 0){
wait(&status);
printf("I'm the parent P0.PID=%d, PPID=%d.\n", getpid(), getppid());}
else{
printf("I'm the child P1 my parent is P0. PID=%d, PPID=%d.\n", getpid(), getppid());
pid2=fork();
if (pid2!=0){
printf("I'm the child P2 and parent to p3,p4,p5.PID=%d, PPID=%d.\n", getpid(), getppid());
pid3=fork();
if (pid3 == 0){
printf("I'm the child P3.PID=%d, PPID=%d.\n", getpid(), getppid());
}
else {
pid4=fork();
if(pid4 == 0)
{
printf("I'm the child P4.PID=%d, PPID=%d.\n", getpid(), getppid());
} else{
pid5 = fork();
if(pid5 == 0)
{
printf("I'm the child P5.PID=%d, PPID=%d.\n", getpid(), getppid());
}
}
}
}
}
/*
if(getppid(&pid1)==getppid(&pid5)){
execl("/bin/ps","ps","-f",(char *)NULL);
}*/
return 0;
}
P0
/ \
P1 P2
/ | \
P3 P4 P5
【问题讨论】:
-
P0 在分叉 P2 之前调用
wait()。它只在等待 P1。 -
@JohnBollinger 你好,我刚接触堆栈溢出(我什至不知道基础知识)。再次感谢您帮助我。
-
您需要在
if(pid5==0)中添加一个else块,在循环中调用wait()以等待2 个孩子。 -
@barmar 谢谢,我太糟糕了,至少我在努力。
-
请注意,如果输出不是到 tty(例如,如果您运行此程序时将输出重定向到文件),您将看到一些您可能认为奇怪的行为(行被打印多次)。
标签: c linux parent-child pid