fork() 执行后,父进程和子进程共享代码段。我当时还不清楚子进程运行的时候,到底是从头开始执行还是从 fork() 开始执行。fork 这个单词的字面意思是分叉,按这个逻辑进程应该是从 fork() 这个分叉口继续执行。于是,写了如下代码检验我的推测。
#include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main ( void ) { printf ( "1" ); fork (); printf ( "0/n" ); return EXIT_SUCCESS; } 然后编译运行,执行结果为 10 10 这儿输出了两行“10”,不是表明 prinf ( "1" ); 这条语句在子进程中也被执行了?但随即我也发现代码里有一个笔误:我的本意是让“1”和“0”各自单独成一行,但在“1”后面少加了个“/n”,修改源码后重新编译执行。按照上面的执行结果推断,预测输出的结果 是: 1 0 1 0 但真实的结果是: 1 0 0 前后只相差了一个回车,运行结果却大相径庭。我猜想是因为 printf 输出带有缓冲区,直到回车时才输出缓冲区的内容,同时也清空缓冲区。为验证我的猜想,我另写了一下两段代码。 /** * Linux 的小 Bug * Code 2 * Author: hanxin1987216@163.com */ #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main ( void ) { printf ( "1/n" ); printf ( "2" ); fork (); printf ( "0/n" ); return EXIT_SUCCESS; } /* 执行结果: 1 20 20 */ /** * Linux 的小 Bug * Code 3 * Author: hanxin1987216@163.com */ #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main ( void ) { printf ( "1" ); fflash ( stdout ); fork (); printf ( "0/n" ); return EXIT_SUCCESS; } /* 执行结果: 10 0 */ 看来是对了,问题就是出在缓冲区没有清空,所以子进程在执行 printf() 时把残留在缓冲区里的内容一起输出了。