[英]multiple fork() in c program
#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;
}
Hello, The following code executes 4 forks. 您好,以下代码执行4个派生。 At first the original process(Lets call it P0) executes the "pid1=fork()" and creates a child(Lets call it P1). 首先,原始进程(称为P0)执行“ pid1 = fork()”并创建一个子进程(称为P1)。 Then the original process again executes the pid2=fork() and creates another child(Let's call it P2). 然后,原始进程再次执行pid2 = fork()并创建另一个子级(我们称其为P2)。 Then both the P2 and the P0 execute the "pid3=fork()". 然后,P2和P0都执行“ pid3 = fork()”。 So the P0 creates a third child(Call it P3) and the P2 becomes a parent and creates a child(Call it P4). 因此,P0创建了第三个孩子(称为P3),而P2成为父对象并创建了一个孩子(称为P4)。 And in the end, in the else statement the very first child(P1) creates a child(P5). 最后,在else语句中,第一个孩子(P1)创建一个孩子(P5)。 So the tree is like : 所以树就像:
P0
P1 P2 P3
P5 P4
My question is: Am i right or not? 我的问题是:我对吗? Thanks in advance. 提前致谢。
My question is: Am i right or not? 我的问题是:我对吗?
Yes. 是。
As Paul R says in the comments, try putting some printf's in. For example after 正如Paul R在评论中所说,请尝试放入一些printf。例如
pid1 = fork()
Try putting 试穿
printf("pid %d: pid1 = fork(), result = %d\n", getpid(), pid1);
getpid()
gets the pid of the current process. getpid()
获取当前进程的pid。
#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;
}
I added some printfs and i print the process id and the parent process id but everyone has the same parent. 我添加了一些printfs,并打印了进程ID和父进程ID,但是每个人都有相同的父进程。 Is it because the original process finishes first? 是因为原始过程首先完成? i get this output 我得到这个输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.