为什么 dup2 不按顺序发生?

pos*_*ing 1 c process sequence dup2 dup

这是一个代码片段。

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");
Run Code Online (Sandbox Code Playgroud)

我正在尝试了解 dup 和 dup2。所以我最初将我的 file.txt 连接到 stdout。所以每当我使用 printf 时,我应该写入 file.txt 而不是 stdout。但是,一旦我完成了这种用法,我也想将它恢复回来,所以我最后也使用了 dup2。

问题是文本“This text should go into the file\n”实际上从未进入文件,而是打印在标准输出上。为什么这样?我跟踪它,却发现 dup2 调用发生在 printf("This text..."); 之前。声明,为什么呢?

Bar*_*mar 5

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

printf("This text should go into the file\n");
fflush(stdout);
Run Code Online (Sandbox Code Playgroud)