CareerCup Fork Problem

265 篇文章 1 订阅
86 篇文章 0 订阅
How many times “Hello World” is printed by following program? 
int main() 

if(fork() && fork()) 

fork(); 

if(fork() || fork()) 

fork(); 


printf(“Hello world”); 
return 0; 


a. 16 
b. 20 
c. 24 

d. 64

----------------------------------------------------------------

b.20

----------------------------------------------------------------

pid_t forkvoid);
(pid_t 是一个 宏定义,其实质是int 被定义在# include< sys/types.h>中)
返回值: 若成功调用一次则返回两个值,子进程返回0, 父进程返回子进程ID;否则,出错返回-1

because:

#include <stdio.h>
#include <unistd.h>
using namespace std;
int main() {
  if (fork() && fork())
    printf("Hello World\n");
  return 0;
}

The result is 1 Hello World. Only the parent process could print and the child process couldn't print.

#include <stdio.h>
#include <unistd.h>
using namespace std;
int main() {
  if (fork() || fork())
    printf("Hello World\n");
  return 0;
}

The result is 2 Hello Worlds, the child process will execute the fork after ||, but for && the child process will start after printf. Since the parent process get an ID and child process get an 0. 

#include <stdio.h>
#include <unistd.h>
using namespace std;
int main() {
  if (fork() || fork() || fork())
    printf("Hello World\n");
  return 0;
}

The result is 3 Hello World.

#include <stdio.h>
#include <unistd.h>
using namespace std;
int main() {
  if (fork() || fork() || fork())
    fork();
  printf("Hello World\n");
  return 0;
}

7 Hello worlds!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值