c程序中的多个fork()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid1, pid2, pid3, pid4;
pid1=fork();
if (pid1!=0) {
pid2=fork();
pid3=fork();
}else {
pid4=fork();
}
return 0;
}
你好, 以下代码执行4次分支。起初,原始程序(让我们称之为P0)执行“pid1 = fork()”并创建一个子程序(让它称为P1)。然后原始进程再次执行pid2 = fork()并创建另一个子进程(我们称之为P2)。然后P2和P0执行“pid3 = fork()”。因此,P0创建了第三个孩子(称为P3),P2成为父母并创建一个孩子(称为P4)。最后,在else语句中,第一个孩子(P1)创建一个孩子(P5)。因此,树是这样的:c程序中的多个fork()
P0
P1 P2 P3
P5 P4
我的问题是:我说的对不? 在此先感谢。
我的问题是:我说的对不?
是的。
正如保罗 - [R说,在评论,尝试把一些的printf在例如后
pid1 = fork()
尝试把
printf("pid %d: pid1 = fork(), result = %d\n", getpid(), pid1);
getpid()
获取当前进程的PID。
使用'getppid()'可能是也有帮助。 –
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid1, pid2, pid3, pid4;
printf("PID=%d, PPID=%d.\n", getpid(), getppid());
pid1=fork();
if (pid1!=0) {
pid2=fork();
printf("PID=%d, PPID=%d.\n", getpid(), getppid());
pid3=fork();
printf("PID=%d, PPID=%d.\n", getpid(), getppid());
}else {
pid4=fork();
printf("PID=%d, PPID=%d.\n", getpid(), getppid()); }
return 0;
}
我添加了一些printfs,我打印进程ID和父进程ID,但每个人都有相同的父母。是因为原来的流程先完成?我得到this output
确实他们是6个不同的过程,但他们的父母并不像我上面描述的 –
使用调试器和/或添加一些调试'printf's和检查自己 - 你会学到更多的方式。 –
不是pid2 = fork();返回两次(父母和子女),所以pid3 = fork90;将执行两次。 –
@DavidZimmerman是的,这就是提问说,为什么在他的树形图的数字上升到5 – JeremyP