dup2后的奇异现象
我写了这样一个程序:
#include <stdio.h>#include <fcntl.h>#include <unistd.h>int main( ){ int fd = open("file", O_CREAT|O_WRONLY, 0644); int newfd = dup(1); dup2(fd, 1); close(fd); printf("hello\n"); dup2(newfd, 1); printf("world\n"); return 0;}
#include <stdio.h>#include <fcntl.h>#include <unistd.h> int main( ) { printf("start\n"); int fd = open("file", O_CREAT|O_WRONLY, 0644); int newfd = dup(1); dup2(fd, 1); close(fd); printf("hello\n"); dup2(newfd, 1); printf("world\n"); return 0; }
[解决办法]
When the first I/O operation occurs on a file, malloc(3) is called, and a buffer is obtained. If a stream refers to a terminal (as stdout normally does) it is line buffered. The standard error stream stderr is always unbuffered by default.
[解决办法]
楼上正确, ,
应该是由行缓冲变为了全缓冲。
验证如下:
至于你说的在第二个dup2前加个printf的话,hello 输出到文件,world输出到屏幕 的事。。 我试验了仍然是都输出到屏幕 。使用的环境是ubuntu 12.04 LTS.
理解这个行缓冲和全缓冲就行了。 不用太纠缠于太细节的东西 , 因为有些是和实现有关的。 若标准未规定, 则和各自的实现有关 (glibc库的实现)
#include <stdio.h>#include <fcntl.h>#include <unistd.h>int main( ){ int fd = open("file", O_CREAT|O_WRONLY, 0644); int newfd = dup(1); dup2(fd, 1); close(fd); setlinebuf(stdout); printf("hello\n"); dup2(newfd, 1); printf("world\n"); return 0;}