Reading stdout output from a child process

Wed 04 May 2011

I had to deal with a situation in the C language which required reading the stdout from the child process, which was running exec. Since running exec means that the command effectively takes over the process, I needed to make sure whatever it outputted was going back to the parent (as well as still getting the exit value of the exec’d process). I decided to use a pipe to send the stdout to the parent. Usually this is the other way around (where the parent feeds the child input), so it’s a little tricky conceptually. Read this code over a few times, though, and you should get it just fine.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// It's a shame these aren't in unistd.h,
// since it's much easier to read and remember
#define PIPE_READ 0
#define PIPE_WRITE 1

void main ()
{
  int pid, died, exit_status, nbytes;
  int fd[2];
  char buf[4096];

  pipe(fd);

  switch(pid=fork()) {
  case -1:
    // No forking :-(
    printf("Cannot fork, failing");
  case 0:
    // This is the child process
    close(fd[PIPE_READ]);
    dup2(fd[PIPE_WRITE], STDOUT_FILENO);
    execl("/sbin/lspci","lspci",NULL);
  default:
    close(fd[PIPE_WRITE]);
    // This is the parent process
    do {
      died = waitpid(pid, &exit_status, 0);
    } while (!WIFEXITED(exit_status));
    nbytes = read(fd[PIPE_READ], buf, sizeof(buf)-1);
    printf("exit value is: %d\nreceived: %s\n", exit_status, buf);
    close(fd[PIPE_READ]);
  }
}

blogroll

social