c - 无法理解 fork() 的保证

标签 c unix fork

我无法理解是否可以保证 fork() 之后出现.在研究链式过程扇形过程 时,我卡住了。如果我 fork 两次,层次结构大致是

enter image description here

它们是代码的条件:

  • (childpid = fork()) <= 0如果 child 或错误,打破它。 (扇子)
  • (childpid = fork()) > 0如果 parent ,打破它。 (链)

对于 2 个进程的风扇,如图所示

enter image description here

对于 2 个进程链,如图所示

enter image description here

所以我的堆叠点在这里,如何知道哪个 parent 会打破?是否保证首先创建第一个父级(顶部 1)的 fork ,然后再创建另一个父级(左 1)的 fork ?例如,草图可以用于风扇情况吗?为什么? 如果是,在 2 次调用 fork() 的链中,将创建 3 个进程。谁是第三者?据我检查,这是孙子。但在这方面和这种情况下,孙辈是在祖 parent 的 child 之前创建的。

enter image description here

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 是第二个 child 的 parent ,所以有保证。可以肯定的是,我的祖母在我出生之前就生下了我的母亲。

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

原进程调用fork() ; fork()在父项中返回非零子 pid,因此 for循环被打破。它在 child 中返回 0,这意味着循环继续,现在计算 i = 1。 . fork()再次调用并发生同样的事情:for循环由 break 退出。在子进程中,在 i++ 之后, i < n为 false 并退出循环。共fork()被叫了两次。有 3 个进程:原始进程、它的子进程和它的孙进程。该代码创建了这 3 个中的 2

关于c - 无法理解 fork() 的保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955793/

相关文章:

C++ 删除具有有效地址的指针

c - 在 C 中,数组定义中的长度如何映射到寻址?

linux - Shell/bash 中的模式和正则表达式

linux - UNIX基本getopts麻烦

linux - 如何从 IP 地址列表中获取第四个八位字节大于 10 的行?

linux - linux-execve : On executing ls command - get error "ls: cannot access/etc : No such file or directory"

c - 使用 fork 查找矩阵中的数字

c - 检测两个输入引脚上的两个同时信号的最佳实践

c - C 中的局部变量

C:如何屏蔽宏参数中的逗号?