foxcub
foxcub

Reputation: 2567

Duplicate, but still use stdout

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

Upvotes: 5

Views: 1925

Answers (1)

user4815162342
user4815162342

Reputation: 155465

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

Upvotes: 9

Related Questions