-
#include <unistd.h> - #include <stdio.h>
- int main()
- {
- pid_t pid;
- printf( "begin fork\n") ;//line buffer
- write(STDOUT_FILENO ,"write msg befor fork ,buf after printf\n", sizeof("write msg befor fork ,buf after printf\n")-1 );
- pid = fork();
- if ( pid>0 ){
- printf("i am father,pid=%d\n",getpid);
- }else if ( !pid ){
- printf( "i am child.pid=%d\n",getpid);
- }else {
- printf( "fork failed.\n" );
- }
- printf( "this is the end,pid=%d\n", getpid() );
- usleep(1000*100);
- return 0;
- }
运行结果:
[123@localhost unix]$ gcc test.c
[123@localhost unix]$ ./a.out
begin fork
write msg befor fork ,buf after printf
i am father,pid=134513528
this is the end,pid=21127
i am child.pid=134513528
this is the end,pid=21128
[raoliang@localhost unix]$ cat mytest
write msg befor fork ,buf after printf
begin fork
i am father,pid=134513528
this is the end,pid=21141
begin fork
i am child.pid=134513528
this is the end,pid=21142
[raoliang@localhost unix]$
注意发上面两个运行结果不同的地方哦
第一个结果只打印一次begin fork,而第二个结果确打印了两次
从上面一小代码能说明下面几个小问题:
1)printf 到终端是行缓冲(标准I/O是有缓冲区的)
2)write没有缓冲(把write中的\n去掉会更明显一些)
3)文件I/O是全缓冲
4)fork 的子进程和父进程了fork之后的公共的部分,但是只有父进程才执行fork 之前的部分
5)fork后,子进程复制了父进程的缓冲区,包括标准缓冲区的内容(这个就是出现上面结果的真正原因)
由上面的第1、2、5条就很容易理解上面的结果了
当输出终端时,printf遇到 换行就直接输出,但是定向的其它的文件的时候,则是全缓冲了,而在清空缓冲前,子进程复制了父进程的缓冲区,所以子进程会再输出一次
OK,就这么多啦
参考:《unix环境高级编程》
转自:http://blog.youkuaiyun.com/rao_warrior/article/details/8249289