I'm interested in two situations:
- How to do it from C++?
- How to do it from system's shell?
Answers for Linux, Windows and OSX are welcome.
I'm interested in two situations:
Answers for Linux, Windows and OSX are welcome.
Linux/OSX (actually POSIX), programming (any language that have POSIX calls), general scheme:
fork()
close(0)
, close(1)
(not necessary, dup2
will close it too... but added for clarity)dup2(socket, 0)
, dup2(socket, 1)
exec()
Shell: use nc
. Example in my other answer: http://stackoverflow.com/questions/1269400/is-this-a-fair-question-to-ask-in-a-software-engineering-interview-phase-1/1269577#1269577
For unix, from a shell: http://www.askdavetaylor.com/how_do_i_reredirect_stdin_in_a_unix_or_linux_shell_script.html
For more general info: http://www.mathinfo.u-picardie.fr/asch/f/MeCS/courseware/users/help/general/unix/redirection.html
For windows, to a socket: http://www.unix.com/high-level-programming/79439-redirect-stdin-out-sockets.html
Here is an explanation on unix, for redirecting: http://www.rtems.com/ml/rtems-users/2007/october/msg00063.html
Now, this one will only be redirecting anything going to stdin/out/err that comes from the program.
I like the fact that the last link also restores stdin/out/err before the program exits. If you make any change like this, restoring is a good thing to remember to do.
There are several ways to do it, you can use pipes, and have the pipe go to a socket or file, for example, so stdin/out would be redirected to a pipe. This is nice if you want to be able to switch where the final destination is going, or if you want to do some processing along the way, as each pipe can do some processing.
I also wonder whether xinetd isn't helpful in this situation. It lets you write a program that simply reads from stdin and writes to stdout, and then xinetd handles listening on some socket, splitting off the necessary i/o sockets, and attaching them to your process.