理解fork()命令Posix API

#include #include #include using namespace std; int main() { fork(); fork(); fork(); fork(); printf("*"); /*This prints 16 stars*/ return 0; } 

使用fork() ,为什么打印16 *?

我知道fork()生成一个新的子进程,它们都执行相同的进程,这可以解释为什么一个fork生成2个星,但是,有四个forks它打印16个,我可以看到它与每个fork()加倍。

但我不明白为什么。 每个fork是否执行下面的函数和参数?

因为第一个fork将分成两个进程,所以这两个进程将调用第二个fork()调用,将这两个进程分成4个。这将继续,直到在每个进程中调用了所有fork()调用。 所以你最终有2^4 = 16调用printf("*")

在“图表”中,每个条形表示调用函数时正在执行的进程数。 因此,函数执行的次数与条数一样多。

  | fork() // The first processes creates a second (2 total) | fork() | // Those 2 processes start 2 more (4 total) || fork() || // Those 4 processes start 4 more (8 total) 

| fork()

| // Those 8 processes start 8 more (16 total)

|| printf()

|| // resulting in 16 calls to printf()

每个fork是否执行下面的函数和参数?

是的,正如您从图中可以看到的,当一个进程分叉创建的进程(以及创建它的进程)继续执行fork之后的下一条指令。

当你调用fork()时,它会创建一个新进程。 您复制了应用程序,然后在fork()调用之后,2个应用程序继续运行并执行新指令

 printf("i'm the main thread\n"); fork(); printf("i'm executed 2 times\n"); fork(); //this fork is so executed 2 times, so 2 new processes, so 4 processes for all printf("i'm excecuted 4 times\n"); fork(); //this fork is executed 4 times to ! So you have now 8 processes; // and etc .. fork(); //this fork is executed 8 times, 16 process now ! printf("*"); // executed 16 times 

新进程在fork()之前共享所有内存,旧的更改状态用于当前线程。 如果你想根据过程做一些事情:

 pid_t p; int i = 1; p = fork(); if(p == 0) { printf("I'm the child\n"); i = 2; exit(0); //end the child process } printf("i'm the main process\n"); printf("%d\n", i); //print 1