linuxstdinsystem-callsfile-descriptordup2

Dup2() usage and output redirection


I'm trying to redirect the output of a process to the stdin of another process. This is done by dup2(). My question is: do stdin and stdout go back to their place(0,1) after function terminates, or do i have to do something like savestdin = dup(0). More clearly, after the function for one command terminates, at the second call are stdin and stdout on their supposed position?


Solution

  • To get your stdout to go to a forked process' stdin, you'll need to use a combination of pipe and dup. Haven't tested it but it should give you some ideas hopefully:

    int my_pipe[2];
    
    pipe(my_pipe); // my_pipe[0] is write end
                   // my_pipe[1] is read end
    
    // Now we need to replace stdout with the fd from the write end
    // And stdin of the target process with the fd from the read end
    
    // First make a copy of stdout
    int stdout_copy = dup(1);
    
    // Now replace stdout
    dup2(my_pipe[0], 1);
    
    // Make the child proccess
    pid_t pid = fork();
    if (pid == 0)
    {
        // Replace stdin
        dup2(my_pipe[1], 0);
        execv(....); // run the child program
        exit(1); // error
    }
    int ret;
    waitpid(pid, &ret, 0);
    
    // Restore stdout
    dup2(stdout_copy, 1);
    close(stdout_copy);
    
    close(my_pipe[0]);
    close(my_pipe[1]);
    

    So to answer your question, when you use dup2() to replace 0 and 1, they will not be restored to the terminal unless you save the original file descriptor with dup() and manually restore it with dup2().