C restore stdout to terminal

前端 未结 3 512
逝去的感伤
逝去的感伤 2020-12-05 05:08

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 t

相关标签:
3条回答
  • 2020-12-05 05:29

    If the program runs on a Linux environment, you can freopen ("/dev/stdout", "a", stdout).

    But if you know that stdout was the terminal, freopen ("/dev/tty", "a", stdout) or the equivalent for other OSs—even Windows.

    0 讨论(0)
  • 2020-12-05 05:30
    #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);
    
    0 讨论(0)
  • 2020-12-05 05:34

    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'.

    0 讨论(0)
提交回复
热议问题