Chao - Testing

testing testing and testing

导航

[unix c]关于FOLK和PRINTF()的一个小问题

#include <unistd.h>
#include <sys/types.h>

main ()
{
pid_t pid;
printf("test");
pid=fork();

if (pid < 0)
printf("error in fork!");
else if (pid == 0)
printf("i am the child process, my process id is %d\n",getpid());
else
printf("i am the parent process, my process id is %d\n",getpid());
}

输出的结果是:
testi am the child process, my process id is 4286
testi am the parent process, my process id is 4285
 
感到很诡异,因为PRINTF是在FOLK之前,此时子进程还没开始,怎么会2个进程都输出"TEST"的?

查了一下资料,发现是PRINTF后,系统并不立即更新STD OUT,而是加在缓冲队列里,所以当时并没有打印,所以会有2次(具体是什么时候打印到屏幕呢?以后再研究)
另外如果使用PRINTF("TEST\N"),"\N"这个回车换行符号会立即更新STD OUT,就只会看到一次"TEST"了.

posted on 2004-11-01 19:41  Chech  阅读(657)  评论(0编辑  收藏  举报