我执行了以下程序,但我对它的输出感到困惑?

时间:2014-10-09 06:56:32

标签: linux fork

我对在执行时创建的子进程没有感到困惑

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i=0;
fork();
fork();
fork();
fork();
pid_t pid;
    if((pid=fork()) == 0) { 
        printf("I am the child: %u\n", getpid());
}
    else {
        printf("I am the parent: %u and my child is: %u\n", getpid(),pid);
    }

return 0;
}

有人可以帮助我理解为什么有这么多的子进程以及为什么每次父ID都不同。

我得到的输出是:

saqlain@ubuntu:~/Desktop$ gcc -c fork.c
saqlain@ubuntu:~/Desktop$ gcc -o fork fork.c
saqlain@ubuntu:~/Desktop$ ./fork
I am the parent: 11842 and my child is: 11847
saqlain@ubuntu:~/Desktop$ I am the child: 11847
I am the child: 11849
I am the parent: 11846 and my child is: 11850
I am the child: 11867
I am the child: 11869
I am the parent: 11843 and my child is: 11856
I am the child: 11850
I am the parent: 11848 and my child is: 11857
I am the parent: 11852 and my child is: 11860
I am the parent: 11845 and my child is: 11849
I am the parent: 11854 and my child is: 11866
I am the child: 11859
I am the child: 11856
I am the child: 11857
I am the parent: 11862 and my child is: 11869
I am the parent: 11865 and my child is: 11870
I am the child: 11860
I am the child: 11866
I am the parent: 11855 and my child is: 11867
I am the parent: 11851 and my child is: 11859
I am the parent: 11863 and my child is: 11871
I am the parent: 11858 and my child is: 11872
I am the parent: 11868 and my child is: 11873
I am the parent: 11844 and my child is: 11861
I am the child: 11870
I am the child: 11861
I am the child: 11864
I am the child: 11872
I am the child: 11871
I am the child: 11873
I am the parent: 11853 and my child is: 11864

1 个答案:

答案 0 :(得分:1)

您正在执行fork 5次,而在第五次执行打印输出。

每个fork将对照分成两个相同的副本,因此2×2×2×2×2 = 32个副本,其中16个基于第五个和最后一个{{1}识别为父母和子女}。