深入理解計算系統,499頁有這麼一個例題。這個例題的輸出會產生多少行?可能順序是什麼?
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <unistd.h>
4 #include<sys/wait.h>
5
6 int main(){
7 int status;
8 pid_t pid;
9 printf("hello\n");
10 pid=fork();
11 printf("%d\n",!pid);
12 if(pid!=0){
13 if(waitpid(-1,&status,0)>0){
14 if(WIFEXITED(status)!=0)
15 printf("%d\n",WEXITSTATUS(status));
16 }
17 }
18 printf("bye\n");
19 exit(2);
20 }
一個可行的輸出結果可能是這樣的:
hello
0
1
bye
2
bye
其中 2,bye是最後要輸出的。因爲父進程要等待子進程的結束。Hello 是第一次要輸出的。
現在我們討論的焦點是,printf("hello\n")會不會被子進程copy ?
在第9行中,去掉“\n" ,結果如下:
hello0
hello1
bye
2
bye
這是因爲不加 "\n"時,”hello"在緩衝區中,未輸出。子進程會copy父進程中的緩衝區。