我想创造这个使用fork()和wait()的混淆,这也是最有效的方法吗?
P0
/\
P1 P2
/| \
P3 P4 P5
使用fork()
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
int main()
{
printf("P0 PID=%d, PPID=%d.\n", getpid(), getppid());
int pid1, pid2, pid3, pid4, pid5;
pid1 = fork();
int status = 0;
if(pid1 != 0){
pid2 = fork();
if(pid2 != 0){
waitpid(pid2, &status, 0); //If father, wait for child P2
printf("%d\n", status);
}
else{
printf("P2 PID=%d, PPID=%d.\n", getpid(), getppid());
pid3 = fork();
if(pid3 != 0){ //If father (P2 at this point)
waitpid(pid3, &status, 0); //Wait for child (P3)
pid4 = fork();
if(pid4 != 0){
waitpid(pid4, &status, 0);
pid5 = fork();
if(pid5 == 0){
printf("P5 PID=%d, PPID=%d.\n", getpid(), getppid());
}
}
else{
printf("P4 PID=%d, PPID=%d.\n", getpid(), getppid());
}
}
else{
printf("P3 PID=%d, PPID=%d.\n", getpid(), getppid());
}
}
}
else{
printf("P1 PID=%d, PPID=%d.\n", getpid(), getppid());
}
return 0;
}
我的目标是使第一个过程等待,直到我P2
过程中确实需要的一切,然后继续。 此行printf("%d\n", status);
用于查看P0
(父级)进程何时继续,但每次都打印在不同的位置。我很困扰。我做对了吗? 此外,这是创建上述内容的最有效方法吗? 谢谢
UPDATE
我改变了一些东西在我的代码(见注释),我现在使用waitpid
。我认为这是正确的。我等待P2结束,P2等待P3,P4结束。 This is the output
谢谢你的时间和你的答案。我会尝试。作为@ Dinos_12345建议使用'waitpid',是否有更好的解决方案? –
'waitpid'给你更多的控制,你可以指定一个特定的进程等待等。在手册页中,您可以看到'wait'等同于'waitpid(-1,&status,0)'。使用哪个可能取决于你使用的是什么。 – GoodDeeds