Posted by: rydow | October 26, 2007

C Code to redirect stdout

This link http://www.cs.purdue.edu/homes/cs354/LectureNotes/Spring2002/week6-3 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);

  close(pipePair[0]);
  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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: