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.
Leave a comment