Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore stdout after using freopen

I try to redirect output in my c++ program from stdout with the following:

 freopen(cmd.c_str(),"w",stdout);    

Then I call system to execute cmd. I have also tried forking and then calling execvp. Either way, when program control returns to my program, things written to stdout are no longer showing. How can normal behavior be restored?

like image 840
neuromancer Avatar asked May 01 '11 05:05

neuromancer


1 Answers

Here is solution for stdin if doing in loop, needed to figure this out for a program wherein freopen of stdin happens in a loop on some condition. Took some time for me to figure out (with help of search and all) and so posting here

savestdin = dup(STDIN_FILENO);  
while (1) {  
        .  
        .  
        if (inputfile) {  
              savestdin = dup(savestdin);
              freopen(inputfile, "r", stdin);  
              restorestdin = TRUE;
         }  
        .  
        .  
        if (restorestdin) {  
              fflush(stdin);  
              fclose(stdin);
              stdin = fdopen(savestdin, "r");  
              restorestdin = FALSE;  
        }  
        .  
        .  

} 
like image 57
shyam Avatar answered Sep 22 '22 01:09

shyam