#includestdio.h#includeunistd.h#includestdlib.h#includeerrno.hint main(){pid_tpid;printf("before fork - with line break\n");printf("before fork - no line break");//fflush(stdout);if( (pid = fork()) 0 ){perror("fork error");exit(1);}else if(
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
pid_t pid;
printf("before fork - with line break\n");
printf("before fork - no line break");
//fflush(stdout);
if( (pid = fork()) < 0 )
{
perror("fork error");
exit(1);
}
else if(pid == 2) /* child */
{
exit(0);
}
sleep(2);
exit(0);
}
/*
$ ./a.out
before fork - with line break
before fork - no line break$ before fork - no line break
$ ./a.out > temp.txt
$ cat temp.txt
before fork - with line break
before fork - no line breakbefore fork - with line break
before fork - no line breakhwx
$ ./a.out # fflush(stdout)
before fork - with line break
before fork - no line break
*/
解释
1、fork()的复制看这里:fork()的一些细节 -
缓冲区也会被复制到子进程的进程空间
2、如果标准输出连接到终端设备,则它是行缓冲的,否则它是全缓冲的。因此,当输出到终端设备时,如果加'\n',调用printf()之后缓冲区会立马被冲刷,输出的内容就不会复制到子进程的进程空间中。
参考资料:
APUE-2e: 5.12, 8.3