Using Dup2 to Redirect Input and Output

user1174511 picture user1174511 · Jul 8, 2013 · Viewed 11.1k times · Source

I have been writing a Unix shell in C, and I am attempting to implement input and output redirection. I have been using Dup2 for this and am able to make it so my output redirects to a file, and my input is redirected correctly as well. However, after I'm done with that, how do I return to using Stdin and Stdout again?

These are the pieces of code I run when redirection is required:

In:

inFile = open(tok.infile, O_RDONLY, 0);
inDup = dup2(inFile, STDIN_FILENO);
close(inFile);

Out:

outFile = creat(tok.outfile, 0644);
outDup = dup2(outFile, STDOUT_FILENO);
close(outFile);

Answer

aah134 picture aah134 · Jul 8, 2013
int stdinHolder = dup(0);
int stdoutHolder = dup(1);
close(0);
close(1);

Then after you are done you can dup back to the holders of stdin and stdout.

int stdinHolder = dup(1);
int stdoutHolder = dup(0);
close(0);
close(1);