Duplicate, but still use stdout

强颜欢笑 提交于 2020-08-07 06:26:08

问题


Is there some magic I can do with dup2 (or fcntl), so that I redirect stdout to a file (i.e., anything written to descriptor 1 would go to a file), but then if I used some other mechanism, it would go to the terminal output? So loosely:

  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

回答1:


A simple call to dup will perform the saving. Here is a working example:

#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;
}


来源:https://stackoverflow.com/questions/35516972/duplicate-but-still-use-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!