系统调用fork输出:
问题描述:
请解释下面的代码输出:系统调用fork输出:
#include<stdio.h>
#include<stdlib.h>
int main(){
if(fork()&&fork()){
fork();
printf("hello");
}
}
输出:hellohello
答
你必须明白fork()的返回两次,一次家长,一旦孩子。孩子得到返回0
和父母得到返回pid
的子进程。知道了这一点,我们可以推理代码:
自C,0是假的,还有什么是真的会发生以下情况:
#include<stdio.h>
#include<stdlib.h>
int main(){
//Create 2 new children, if both are non 0, we are the main thread
//Jump into the if statement, the other 2 children don't jump in and go out of mains scope
if(fork() && fork()){
//Main thread forks another child, it starts executing right after the fork()
fork();
//Both main and the new child print "hello"
printf("hello");
//both main and child return out of if and go out of scope of main.
}
}
应该指出,一旦主要执行第一fork()
那个孩子继续fork()
自己的孩子。但由于&&
运营商,该子女得到(0 && somepid)
评估为false,这就是为什么你没有得到3 hello。
Aww,不,不是! – 2013-08-06 16:24:02