为什么 dup2 不按顺序出现?

Why doesn't dup2 occur in sequential order?

这是一个代码片段。

int saved_stdout = dup(1);
int fd = open("file.txt", O_WRONLY | O_CREAT, 0640);

close(1);
dup(fd);
close(fd);

printf("This text should go into the file\n");

//restore stdout
dup2(saved_stdout, 1);
printf("stdout restore");

我正在尝试了解 dup 和 dup2。所以我最初将我的 file.txt 连接到标准输出。因此,每当我使用 printf 时,我都应该写入 file.txt 而不是标准输出。但我也想在完成此用法后恢复它,所以我最后也使用 dup2。

问题是文本 "This text should go into the file\n" 从未真正进入文件,而是打印在标准输出上。为什么这样?我搜索了一下,结果发现 dup2 调用发生在 printf("This text..."); 之前。声明,为什么这样?

我删除了我之前的答案,因为它是错误的....但是当你使用 printf() 时,你正在使用 FILE * 作为 stdout,其中有一个描述符或指向终端的东西。更改 fd 1 显然不会改变它。

我得到的测试结果不一致,所以在这里放弃。我只想补充一点,将此行放在 open() 之后对我有用,这突出了晦涩的行为:

printf("fileno is %i\n", fileno(stdout));

不要将 FILE *printf() 操作与文件描述符操作混合。您应该将 write() 与描述符一起使用。

问题可能是由于输出缓冲。如果 stdout 不写入终端,则它是完全缓冲的,因此当您使用 dup() 将其重定向到文件时,它将被缓冲。尝试在 printf().

之后刷新输出
printf("This text should go into the file\n");
fflush(stdout);