Search code examples
c++linuxpipefile-descriptor

how to get back stdout after piping it with dup?


int mypipe[2];
pipe(mypipe);
int dupstdout=dup2(mypipe[1],1);
cout<<"hello";//not printed on terminal
fflush(stdout);

now how to print again on terminal or redirect mypipe[0] to stdout?


Solution

  • #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    int main() {
        int mypipe[2];
        pipe(mypipe);
        int dupstdout=dup2(mypipe[1], 1);
        printf("hello");//not printed on terminal
        fflush(stdout);
    
        close(dupstdout);
    
        int fd = open("/dev/tty", O_WRONLY);
        stdout = fdopen(fd, "w");
    
        printf("hello again\n");
    }
    

    Anyway, it's better to not close stdout.

    If a descriptor passed as a second argument to dup2() is already opened, dup2() closes it ignoring all errors. It's safer to use close() and dup() explicitly.