Re: Capture stdout and stderr from child process

From: Barry Margolin (barry.margolin_at_level3.com)
Date: 08/29/03


Date: Fri, 29 Aug 2003 19:24:51 GMT

In article <151c6c1d.0308291106.56788cbb@posting.google.com>,
Peter Tan <shiuyuan@yahoo.com> wrote:
> I am trying to capture standard output and error from unix shell
>running as a child process. I understand that to do so, I need to use
>pseudo terminal. But the problem is the slave side combine stdout and
>stderr nad print them out together on the terminal. My question is if
>there is a way to separate stderr and stdout?

You don't need to use a pseudo terminal for this, just use two pipes.

int stdout_pipe[2];
int stderr_pipe[2];

pipe(stdout_pipe);
pipe(stderr_pipe);

switch (fork()) {
  -1: /* handle fork error */
     break;
   0: /* child */
      close(stdout_pipe[0]);
      dup2(STDOUT_FILENO, stdout_pipe[1]);
      close(stdout_pipe[1]);
      close(stderr_pipe[0]);
      dup2(STDERR_FILENO, stderr_pipe[1]);
      close(stderr_pipe[1]);
      execl("/bin/sh", ...);
      break;
   default:
      close(stdout_pipe[1]);
      close(stderr_pipe[1]);
      /* Now you can read from stdout_pipe[0] and stderr_pipe[0] to get the
         child's stdout and stderr */
      ...
}

-- 
Barry Margolin, barry.margolin@level3.com
Level(3), Woburn, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.


Relevant Pages

  • Capture stdout and stderr from child process
    ... I am trying to capture standard output and error from unix shell ... running as a child process. ... stderr nad print them out together on the terminal. ... there is a way to separate stderr and stdout? ...
    (comp.unix.programmer)
  • Re: does IO.read block?
    ... Assume an application as a child process that frequently writes to stdout and stderr. ... The parent process at the other end of those two pipes only reads the stdout pipe. ...
    (comp.lang.ruby)
  • Re: [ANN] open4-0.8.0
    ... $ sudo gem install open4 ... open child process with handles on pid, stdin, stdout, and stderr: ...
    (comp.lang.ruby)
  • [ANN] open4-0.8.0
    ... open child process with handles on pid, stdin, stdout, and stderr: ... include Open4 ...
    (comp.lang.ruby)
  • Re: How does one effect O_NONBLOCK?!
    ... would get the child process to react exactly the same way as ... it would if its stdout would be connected to a terminal (that's ... changed the default buffering mode). ... I'm sure I won't need pseudo-terminals for pkg- ...
    (comp.unix.programmer)