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

fox*_*cub 3 c unix file dup2

我可以用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
Run Code Online (Sandbox Code Playgroud)

use*_*342 6

一个简单的调用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;
}
Run Code Online (Sandbox Code Playgroud)

  • 可能想要使用`STDOUT_FILENO`而不是魔术数字. (2认同)