Home > OS >  How do you read errors into a pipe in c?
How do you read errors into a pipe in c?

Time:08-06

How do you read stderr when using execvp, running a command that outputs and error in the terminal using this script will result in an empty buffer (no text)

int cmd(char * const *cmd, char * output)
{
    int pipefds[2], r, status, x;  
    pid_t pid;

    if (pipe(pipefds) == -1){
        return -1;
    }
    if ( (pid = fork()) == -1){
        return -1;
    }

    if (pid == 0)
    {
        dup2(pipefds[1], STDOUT_FILENO);
        close(pipefds[0]);
        close(pipefds[1]);
        execvp(cmd[0] , cmd);
    }
    else
    {
        close(pipefds[1]);
        x = read(pipefds[0], output, 16384);
        wait(NULL);
    }
    return 0;
}

all the resources that I found online do not seem to mention where/how to pipe the error into the buffer, what are the three file descriptors in pipefds one for stdin another for stdout what about the last one stderr?

CodePudding user response:

Before calling execvp, set it up so that file descriptor STDERR_FILENO (i.e. 2) goes to the pipe.

You can simply dup it an extra time, e.g.:

dup2(pipefds[1], STDOUT_FILENO);
dup2(pipefds[1], STDERR_FILENO);

now both file descriptors 1 (stdout) and 2 (stderr) point to the same pipe.

  • Related