Posted by: rydow | October 26, 2007

C Code to redirect stdout

This link gives a good understanding on what happens in the below code:

static int pipePair[2];
static int oldstdout;

static int redirectStdOut(void)
  oldstdout = dup(STDOUT_FILENO);

  if ( pipe(pipePair) != 0){
    return -1;

  dup2(pipePair[1], STDOUT_FILENO);
  close (pipePair[1]);
  return pipePair[0];
static void restoreStdOut(void)
  dup2(oldstdout, STDOUT_FILENO);

  pipePair[0] = -1;

The above is by no means meant to be complete, but gives an implementation to start from when testing code that uses e.g. printf. Reading the pipePair[0] gives what printf etc. would have written to stdout. We have essentially made ourselves a printf stub.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: