fork (); // Line 1 fork (); // Line 2 fork (); // Line 3
L1 // There will be 1 child process / \ // created by line 1. L2 L2 // There will be 2 child processes / \ / \ // created by line 2 L3 L3 L3 L3 // There will be 4 child processes // created by line 3
问题1
如下的程序会输出什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<stdio.h> #include<sys/types.h> #include<unistd.h> voidforkexample() { // child process because return value zero if (fork() == 0) printf("Hello from Child!\n");
// parent process because return value non-zero. else printf("Hello from Parent!\n"); } intmain() { forkexample(); return0; }
1 2 3 4 5 6 7 8
1. Hello from Child! Hello from Parent! (or) 2. Hello from Parent! Hello from Child! //因为子进程与父进程是在同时运行的,所以哪一个先输出是不确定的
#include<stdio.h> #include<sys/types.h> #include<unistd.h> voidforkexample() { pid_t pid; pid = fork(); // child process because return value zero if (pid == 0) printf("Hello from Child!\n");
// parent process because return value non-zero. else printf("Hello from Parent!\n"); } intmain() { forkexample(); return0; }
if (fork() == 0) printf("Child has x = %d\n", ++x); else printf("Parent has x = %d\n", --x); } intmain() { forkexample(); return0; }
1 2 3 4 5
Parent has x = 0 Child has x = 2 (or) Child has x = 2 Parent has x = 0
解析
子程序和父程序在fork之前的东西是共享的,但是在fork之后的东西就都是各自的了。
思考题目
下面的程序总共会创建多少子进程
1 2
for (i = 0; i < n; i++) fork();
2^n - 1
1 2 3 4 5 6 7
F0 // There will be 1 child process created by first fork / \ F1 F1 // There will be 2 child processes created by second fork / \ / \ F2 F2 F2 F2 // There will be 4 child processes created by third fork / \ / \ / \ / \ ............... // and so on
如下的程序打印结果,假设父进程打印的值为x y , 子进程打印的值为u v,那么这四个值之间的关系为? u + 10 = x and v = y
1 2 3 4 5 6 7 8
if (fork() == 0) { a = a + 5; printf("%d, %p\n", a, &a); } else { a = a –5; printf("%d, %p\n", a, &a); }