我可以使用dup2
(或fcntl
)做一些魔术,以便将stdout重定向到文件(即,写入描述符1的任何内容都会转到文件中),但是如果我使用其他一些机制,它会转到终端输出?如此松散:
int original_stdout;
// some magic to save the original stdout
int fd;
open(fd, ...);
dup2(fd, 1);
write(1, ...); // goes to the file open on fd
write(original_stdout, ...); // still goes to the terminal
答案 0 :(得分:5)
对dup
的简单调用将执行保存。这是一个有效的例子:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
// error checking omitted for brevity
int original_stdout = dup(1); // magic
int fd = open("foo", O_WRONLY | O_CREAT);
dup2(fd, 1);
write(1, "hello foo\n", 10); // goes to the file open on fd
write(original_stdout, "hello terminal\n", 15); // still goes to the terminal
return 0;
}