首页 > 其他 > 详细

CareerCup Fork Problem

时间:2014-02-23 15:11:17      阅读:381      评论:0      收藏: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!



CareerCup Fork Problem

原文:http://blog.csdn.net/taoqick/article/details/19714105

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!