I'm writing a function, which, given an argument, will either redirect the stdout to a file or read the stdin from a file. To do this I close the file descriptor associated with the stdout or stdin, so that when I open the file it opens under the descriptor that I just closed. This works, but the problem is that once this is done, I need to restore the stdout and stdin to what they should really be.
What I can do for stdout is open("/dev/tty",O_WRONLY); But I'm not sure why this works, and more importantly I don't know of an equivalent statement for stdin.
So I have, for stdout
close(1);
if (creat(filePath, O_RDWR) == -1)
{
exit(1);
}
and for stdin
close(0);
if (open(filePath, O_RDONLY) == -1)
{
exit(1);
}
You should use dup() and dup2() to clone a file descriptor.
However, there's a minor detail you might want to be careful with (from man dup):
If this is a problem, you might have to restore the close-on-exec flag, possibly using dup3() instead of dup2() to avoid race conditions.
Also, be aware that if your program is multi-threaded, other threads may accidentally write/read to your remapped stdin/stdout.
You could create a child process, and set up the redirection inside the child only. Then wait for the child to terminate, and continue working in the parent process. That way you don't have to worry about reversing your redirection at all.
Just look for examples of code using fork() and wait ().
I think you can "save" the descriptors before redirecting:
Later on you can use
dup2
to restore them:I am not doing any error checking in that example - you should.