Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you read errors into a pipe in c?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading