使用 fork() 的并发进程

标签 c concurrency process fork scheduling

我得到以下代码:

main()
{
int i, rc;
 for (i = 0; i<=1; i++)
 {
   if( (rc=fork()) == 0)
   {
    printf("Child %d executing\n",i);
   }  /*end if*/
 } /*end for*/ 
}
printf("All children created\n");

我还得到了输出可能出现的可能排列的解决方案。

Child 0 executing |

Child 1 executing | Child 1 All children created |

Child 1 executing | Child 2 All children created |

Child 1 executing | Grand child All children created |

All children created | Parent

我知道这些输出是由每个进程创建的,但我只是无法跟踪它们以了解这些输出如何发生。我知道 fork() 创建一个进程,而 if (fork() == 0) 意味着它是一个子进程,但是如果有人可以帮助我理解答案在哪里子 0 执行 | 来了,谢谢。我相信|只是当前正在运行的进程的描述。为什么child 1可以创建“孙子”,而child 0却不能?

最佳答案

首先,如果展开循环,代码和行为将更容易理解。代码则变为:

int rc;

if ((rc = fork()) == 0)
    printf("Child 0 executing\n");                                          

if ((rc = fork()) == 0)
    printf("Child 1 executing\n");

printf("All children created\n");

然后,为了帮助理解发生了什么,最好的方法是将流程层次结构绘制为树。这是它的 ASCII 版本:

                main
                /|
               / |
              /  |\
          child0 | \
            |    |  \
            |    | child1
           /|    |   |
          / |    |   |
         /  |    |  end
        /  end   |   
       /         | 
    child1      end  
      |             
      |             
     end     

在图中,child0 是显示“Child 0 执行”的 printf 语句,child1 是“Child 1 执行”语句,“end”是显示“所有子项已创建”的 printf 语句。

正如您从图表中看到的,您将获得 1x child0、2x child1 和 4x“所有子级已创建”。

更新@bkennedy

这是另一个仅显示进程 View 的 View ,其中 P0 是主(原始)进程,“end”表示每个进程的完成:

                P0
                /|
               / |
              /  |\
            P1   | \
            |    |  \
            |    |  P2   
           /|    |   |
          / |    |   |
         /  |    |  end
        /  end   |   
       /         | 
      P3        end  
      |             
      |             
     end     
  • 实际上有 4 个进程:P0(主进程)、P1、P2 和 P3。
  • P1 是 P0 的第一个子节点;它显示“Child 0 running”。
  • P2 是 P0 的第二个子级;它显示“子进程 1 正在执行”。 P2 从不创建任何子级,它只是以 printf 语句结束。
  • P3 是 P1 的第一个(也是唯一的)子级。
  • 每个进程完成后都会显示“所有子进程已创建”。

记住:

  • P0(主)经历 2 次 fork 调用,因此有 2 个子项。
  • P1 经过 1 次 fork 调用,因此是单个子进程 (P3)。
  • P2 永远不会经历 fork 调用。

就这样,没有创建其他进程。我不知道如何向您更好地解释这一点。

关于使用 fork() 的并发进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142134/

相关文章:

c# - 并发冲突 : the UpdateCommand affected 0 of the expected 1 records

java - Java对象的并发

android - 我可以在 UI 线程上调用方法时阻止我的服务线程吗?

Java 运行异步进程

C - for 循环代码之间的差异

c - 单击箭头按钮时滚动条位置增加多少?

c - 如何通过错误处理和调试减少 C 中的代码膨胀

c++ - 高效计算 32 位整数乘法的高阶位

c - 其他进程的GetCommandLine()?

c# - 为什么即使进程确实存在,Process.WaitForExit 也会抛出 "no process"异常?