重复,但仍然使用标准输出

Duplicate, but still use stdout

我可以用 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

只需调用 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);
  close(fd);                                      // not needed any more
  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;
}