Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate, but still use stdout

Tags:

c

file

unix

dup2

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
like image 353
foxcub Avatar asked Mar 13 '23 05:03

foxcub


1 Answers

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;
}
like image 75
user4815162342 Avatar answered Mar 20 '23 05:03

user4815162342