Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C restore stdout to terminal

Tags:

I am working with a multi-thread program.

First I redirect my stdout to a certain file. No problem there (I used dup2(fd, 1) where fd is the file descriptor for the file).

Afterwards, I need to redirect my stdout to the terminal again.

My first approach:

      /*Declaration*/       fpost_t  stream_sdout;       /*code*/       if ( fgetpos( stdout, &stream_sdout) == -1 )           perror(Error:); 

It says illegal seek.
No idea why this is happening.
But if I get this to work, then I only need to use fsetpos(stdout, &stream_stdout) and it should work.

My second idea, was to to copy the stdout using dup2(stdout, 4) to the file descriptor table, at position 4. But that ain't working either.

How can I switch the standard output back to its original destination (terminal, pipe, file, whatever)?

like image 971
Alessandroempire Avatar asked Jun 14 '12 22:06

Alessandroempire


People also ask

How do I use stdout to file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.


2 Answers

#include <unistd.h>  ...  int saved_stdout;  ...  /* Save current stdout for use later */ saved_stdout = dup(1); dup2(my_temporary_stdout_fd, 1);  ... do some work on your new stdout ...  /* Restore stdout */ dup2(saved_stdout, 1); close(saved_stdout); 
like image 61
pilcrow Avatar answered Sep 16 '22 21:09

pilcrow


Before you do the dup2(fd, STDOUT_FILENO), you should save the current open file descriptor for standard output by doing int saved_stdout = dup(STDOUT_FILENO); (letting dup() choose an available file descriptor number for you). Then, after you've finished with the output redirected to a file, you can do dup2(saved_stdout, STDOUT_FILENO) to restore standard output to where it was before you started all this (and you should close saved_stdout too).

You do need to worry about flushing standard I/O streams (fflush(stdout)) at appropriate times as you mess around with this. That means 'before you switch stdout over'.

like image 30
Jonathan Leffler Avatar answered Sep 19 '22 21:09

Jonathan Leffler