views:

200

answers:

3

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.

+2  A: 

Linux/OSX (actually POSIX), programming (any language that have POSIX calls), general scheme:

  1. setup a socket...
  2. fork()
  3. close(0), close(1) (not necessary, dup2 will close it too... but added for clarity)
  4. dup2(socket, 0), dup2(socket, 1)
  5. 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

liori
If I use: nc -e "program args" it doesn't work. Any way around it?
Łukasz Lew
Use `nc -c "/full/path/to/program args"`.
liori
fork() is not needed.
Łukasz Lew
If you don't have anything other to do after calling the program, then yes, it is not needed. But this case is pretty rare... I guess only for smaller programs.
liori
A: 

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.

James Black
+3  A: 

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.

Jonathan Feinberg