Re: sockets, fork() & makefile()

Guido.van.Rossum@cwi.nl
Mon, 21 Dec 1992 18:35:44 +0100

>I'm trying to open a socket, fork(), dup a file descriptor with makefile(),
>assign to sys.stdin and exec() another procedure.
>
>And it's not working quite right.
>Should it?
>
>The assignment to stdin and exec is the bit that I am suspicious of - will
>python actually export that assignment ?

No, I'm sorry, it doesn't. I suggest you use popen() and construct a
piece of shell syntax to redirect the socket's file number to 0,
something like

sock = socket(...) # Create a socket
cmd = 'some_program arg1 arg2 ...' # A command and its arguments
fd = sock.fileno() # Get the socket's file number as an integer
cmd = cmd + ' 0<&' + `fd` # Append "0&<N" where N is the file number
pipe = os.popen(cmd, 'w') # Fork+exec the program; it ignores its stdin
pipe.close() # Write an EOF on the pipe

I could hack something in exec() to dup the file descriptors from
sys.std{in,out,err} back to 0, 1, 2, except that (in a yet unreleased
version) it is possible to replace any file with a class instance, as
long as the instance has a write() method or read() and readline()
methods. In this case, what should I use for the file descriptor in
the exec'ed process?

Maybe it's better to provide low-level operations posix.dup(i),
posix.open(...), posix.close(i) etc. and an fdopen()-like interface,
so that if necessary you can do anything you like yourself (some
programs may want special files open as fd 5...). This, however, has
the disadvantage that uninformed use can cause unexplainable problems,
e.g. what if a novice user accidentally closes fd 1...

--Guido van Rossum, CWI, Amsterdam <guido@cwi.nl>
"Look matey, this parrot wouldn't voom if I put four thousand volts
through it"