According to the following program with fork() system call, explain what the output will be at Line A. Suppose all fork() system calls succeed.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int value = 5;
pid_t pid;
pid = fork();
value += 10;
pid = fork();
value += 10;
if (pid == 0) {
value += 15;
return 0;
} else if (pid > 0) {
wait(NULL);
printf("%d\n", value); /* LINE A */
return 0;
}
}
(a) 5. (b) 15. (c) 25. (d) 40. (e) 45.
每個 process 各自有一份 value,fork 不共用
第一次 fork 後 \(+10\),第二次 fork 後再 \(+10\) → 走到 if 前每個 process 的 value 都是 \(5+10+10=25\)
\(\text{pid}==0\) 的 process(第二次 fork 的 child)才 \(+15\),直接 return,沒有印
LINE A 只有 \(\text{pid}\gt0\) 的 process 會執行(第二次 fork 的 parent),value 是 25
原 parent 與第一次 fork 的 child 各有一個 child,各自 wait 完印一次,共印兩行,內容都是 25
(c)