2

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);
user1174511
  • 309
  • 3
  • 5
  • 15
  • I think you should re-experiment, and find out, I will try to dub2 to 0 and 1 back, if you didnt close them. – aah134 Jul 08 '13 at 02:22

1 Answers1

1
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);
Andrew Pierno
  • 510
  • 4
  • 12
aah134
  • 860
  • 12
  • 25