c - 为什么进程总数是2

标签 c operating-system fork

我想弄清楚为什么这条语句会产生 2 个进程

if(fork()&&(fork()||fork()))
 printf("Hello");

我了解短路问题,而且我知道如果不使用 if 执行此语句,我们将总共获得 4 个进程。那么你能解释一下通过在这样的语句中插入 if 来使用的标准吗?

最佳答案

应该创建了 4 个进程。您可以通过在 if 语句之后放置一个额外的 printf 调用来轻松验证这一点。

printf("Hello") 只运行了两次,因为只有其中两个进程的条件为真。

具体来说,根进程产生了两个子进程,第二个子进程又产生了一个:

<parent> : condition is true because the two first fork calls return non-0 : (true && (true || ??))
  <child1> : condition is false because the first fork returns 0: (false && (?? || ??))
  <child2> : condition is true because the first and third fork calls return non-0: (true && (false || true))
    <child3> : condition is false because the second and third fork calls return 0: (true && (false || false))

关于c - 为什么进程总数是2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299306/

相关文章:

c - C 语言中的 IFIFO 文件

c - 运行最小 OpenMP 程序时的非法指令

c - 从 C 中的 MMAP 中删除空格

multithreading - 解决死锁: Lock Ordering

java - 断电期间文件操作如何执行

c++ - 如何使用 fork() 系统调用创建一级进程树?

c - 指向 malloc 的指针?

c - WSAStartup 函数如何启动 Winsock DLL 的使用?

operating-system - bios和实模式

c++ - 这段 C 代码是做什么的?