c - fork() 和二叉树创建

标签 c fork binary-tree

如何为以下代码创建二叉树?

#include <stdio.h>
#include <unistd.h>
int main()
{
   fork();
   fork() && fork() || fork();
   fork();

   printf("forked\n");
   return 0;
}

基本上我无法解决逻辑运算符条件。对于无条件的 fork() 语句,它可以很容易地完成,但是上面的代码呢? 供引用,这里是链接 http://www.geeksforgeeks.org/fork-and-binary-tree/

最佳答案

#include <stdio.h>
int main()
{
   fork(); /* A */
   ( fork()  /* B */ &&
   fork()  /* C */ ) || /* B and C are grouped according to precedence */
   fork(); /* D */
   fork(); /* E */

   printf("forked\n");
   return 0;
}
  • 有 5 个 fork 调用(A、B、C、D、E)。
  • 程序从一个主线程(m)开始。
  • 执行 fork 时,将创建一个新的子进程。 (三)

因此,根据显示的图表,每个节点将总是有 2 个子节点。

  • 左边的节点永远是创建进程(m)
  • 右边的节点是子进程。

“On success, the PID of the child process is returned in the parent, and 0 is returned in the child.”

让我们看看 fork B。 父进程(m)将返回一个非负数的 pid,子进程(c1)返回 0。

  • 因此,父进程执行fork C,但跳过fork D 由于 short circuit evaluation .

    (1234 && 4392) || fork()

  • 新创建的子进程跳过fork C,执行fork D 出于上述原因。

    (0 && fork() ) || fork()

enter image description here

关于c - fork() 和二叉树创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22708839/

相关文章:

c - 为什么我无法访问所定位的内存?

c - 为什么调用AddNode()函数后大小等于二叉树中添加的数据?

c - 为什么 NULL 不是有效的内存地址?

c - 根据\n 将字符数组分成多个部分

Node.js、集群模式、日志聚合和logrotate

child 使用pause()收到信号后不继续运行

c# - 网格的最优高密度二元空间划分

algorithm - 在 BST 中打印后继者和前任者

c - 在 libpcap pcap_loop() 回调上传递参数

c - 失效进程,fork()