为什么这个程序会打印“forked!"?4次? [英] Why does this program print "forked!" 4 times?

查看:42
本文介绍了为什么这个程序会打印“forked!"?4次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个程序会打印forked!"4次?

Why does this program print "forked!" 4 times?

#include <stdio.h>
#include <unistd.h>

int main(void) {

  fork() && (fork() || fork());

  printf("forked!
");
  return 0;
}

推荐答案

第一个 fork() 在调用进程中返回一个非零值(称之为 p0),在子进程中返回 0(称之为 p1).

The first fork() returns a non-zero value in the calling process (call it p0) and 0 in the child (call it p1).

在 p1 中,对 && 进行短路,进程调用 printf 并终止.在 p0 中,进程必须计算表达式的其余部分.然后它再次调用fork(),从而创建一个新的子进程(p2).

In p1 the shortcircuit for && is taken and the process calls printf and terminates. In p0 the process must evaluate the remainder of the expression. Then it calls fork() again, thus creating a new child process (p2).

在p0中fork()返回一个非零值,取||的短路,所以进程调用printf并终止.

In p0 fork() returns a non-zero value, and the shortcircuit for || is taken, so the process calls printf and terminates.

在 p2 中,fork() 返回 0,所以 || 的余数必须求值,也就是最后一个fork();这导致为 p2 创建一个子节点(称为 p3).

In p2, fork() returns 0 so the remainder of the || must be evaluated, which is the last fork(); that leads to the creation of a child for p2 (call it p3).

P2 然后执行 printf 并终止.

P2 then executes printf and terminates.

P3 然后执行 printf 并终止.

P3 then executes printf and terminates.

然后执行 4 个 printf.

这篇关于为什么这个程序会打印“forked!"?4次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆