无法理解 fork() 的保证

unable to understand guarantee of fork()

我无法理解fork()之后是否有保证。在研究 chain processfan process 时,我卡住了。如果我分叉两次,层次结构大致是

它们是代码的条件:

对于 2 个进程的风扇,显示草图

对于 2 个进程链,显示草图

所以我的堆叠点在这里,如何知道哪个 parent 会损坏?是否可以保证首先创建 parent 的(top 1)分叉,然后再创建其他 parent 的(left 1)?例如,草图可以用于风扇情况吗?为什么? 如果是,在 2 次调用 fork() 的链中,将创建 3 个进程。谁是第三者?据我检查,它是 grandchild。但在这方面和这种情况下,grandchild 是在 grandparent 的 child.

之前创建的

simplechain.c

/* UNIX Systems Programming: Communication, Concurrency and Threads 2nd 
   Edition, Kay Robbins and Steven Robbins */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
   pid_t childpid = 0;
   int i, n;

   n = 2;
   for (i = 0; i < n; i++)
      if (childpid = fork())
         break;

   fprintf(stderr, "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
           i, (long)getpid(), (long)getppid(), (long)childpid);
   return 0;
}

simplefan.c

/* UNIX Systems Programming: Communication, Concurrency and Threads 2nd 
   Edition, Kay Robbins and Steven Robbins */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
   pid_t childpid = 0;
   int i, n;

   n = 2;
   for (i = 0; i < n; i++)
      if ((childpid = fork()) <= 0)
         break;

   fprintf(stderr, "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
           i, (long)getpid(), (long)getppid(), (long)childpid);
   return 0;
}

Is there a guarantee first parent's(top 1) fork will be created firstly, then the other parent's(left 1) will be created secondly? For example can the sketch be possible for fan situation? Why?

第一个parent的child是第二个的parent,所以有保证。可以肯定的是,我的祖母在我出生之前就生下了我的母亲。

总共有3个进程。一个 fork() 调用有一个原始进程,它创建一个 child 进程。

原进程调用fork()fork() returns non-zero child pid in parent 所以 for 循环被打破了。它 returns 0 in child,这意味着循环继续,现在计算 i = 1。再次调用 fork() 并发生同样的事情:for 循环被 break 退出。 child过程中,i++后,i < n为false,退出循环。总共 fork() 被调用了两次。有 3 个进程:原始进程、它的 child 和它的 grandchild。代码创建了 2 3.