为什么这个程序的打印"叉&QUOT!; 4次? [英] Why does this program print "forked!" 4 times?

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

问题描述

为什么这个程序打印叉!4倍?

 的#include<&stdio.h中GT;
#包括LT&;&unistd.h中GT;诠释主要(无效){  叉()及&放大器; (叉()||叉());  的printf(分叉\\ n!);
  返回0;
}


解决方案

第一个叉()返回调用过程中一个非零值(称之为P0)而在孩子0(称之为P1)。

在P1为&安培的短路;&安培; 拍摄后,进程调用的printf 并终止。在P0过程中必须评估除权pression的剩余部分。然后调用叉()再次,从而创建一个新的子进程(P2)。

在P0 叉()返回一个非零值,以及 || 的短路服,所以这个过程调用的printf 并终止。

在P2,叉()返回0所以的剩余||必须进行评估,这是最后一个叉();这导致创建一个孩子为P2(称之为P3)。

P2然后执行的printf 并终止。

P3然后执行的printf 并终止。

4 的printf ,则再执行。

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

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

int main(void) {

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

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

解决方案

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

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).

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

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 then executes printf and terminates.

P3 then executes printf and terminates.

4 printfs are then executed.

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

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