Printf的缓冲机制
时间:2007-04-22 来源:ly44770
论坛上的帖子.
有程序如下:
#include <unistd.h>;
#include <sys/types.h>;
main ()
{
pid_t pid;
printf("fork!"); // printf("fork!n");
pid=fork();
if (pid < 0)
printf("error in fork!");
else if (pid == 0)
printf("i am the child process, my process id is %dn",getpid());
else
printf("i am the parent process, my process id is %dn",getpid());
}
结果是
[root@localhost c]# ./a.out
fork!i am the child process, my process id is 4286
fork!i am the parent process, my process id is 4285
但我改成printf("fork!\n");后,结果是
[root@localhost c]# ./a.out
fork!
i am the child process, my process id is 4286
i am the parent process, my process id is 4285
为什么只有一个fork!打印出来了?上一个为什么有2个?
答:printf("AAAAAAAA");//print 一次; 这里会print 2次
如果你将 printf("AAAAAA") 换成 printf("AAAAAA\n") 那么就是只打印一次了.
主要的区别是因为有了一个 \n 回车符号。
这就跟Printf的缓冲机制有关了,printf某些内容时,操作系统仅仅是把该内容放到了stdout的缓冲队列里了,并没有实际的写到屏幕上,但是,只要看到有 n 则会立即刷新stdout,因此就马上能够打印了.
运行了printf("AAAAAA") 后, AAAAAA 仅仅被放到了缓冲里,再运行到fork时,缓冲里面的 AAAAAA 被子进程继承了 ,因此在子进程度stdout缓冲里面就也有了 AAAAAA.
所以,你最终看到的会是 AAAAAA 被printf了2次!!!!
而运行 printf("AAAAAA\n")后, AAAAAA 被立即打印到了屏幕上,之后fork到的子进程里的stdout缓冲里不会有 AAAAAA 内容 ,因此你看到的结果会是 AAAAAA 被printf了1次!