subprocess (spawned by os.system) inherits open TCP/UDP/IP port

Jean-Paul Calderone exarkun at
Fri Jul 20 17:52:53 CEST 2007

On Fri, 20 Jul 2007 08:15:39 -0500, alf <ask at> wrote:
>Jean-Paul Calderone wrote:
>> You can avoid this, if you like.  Set FD_CLOEXEC on the socket after you
>> open it, before you call os.system:
>>  old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
>>  fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
>thx for responding (I was about to send the question to twisted mailing
>list too ;-).
>still would like to find out why it is happening (now FD_CLOEXEC
>narrowed may yahooing/googling searches). While realize that file
>descriptors are shared by forked processes it is still weird why the
>port moves to the child process once parent gets killed. what it the
>parent got multiple subprocesses.

It doesn't actually move.  The file descriptor is a handle onto the port.
A port can have multiple handles which refer to it.  When you fork, you
effectively copy the handle into another process.  Now there are two
handles onto the same port.  If one of the processes exits, the other one
still has a handle, and so the port still exists.  If a process forks
multiple times, then multiple copies are made.  Each process can accept
connections on the port through its own handle.  Exiting just drops the
handle, it doesn't close the port.

>Plus it is kind of unintuitive os.system does not protect from such
>behavoir which is for me more an equivalent of like issuing a ne
>wcommand/ starting a process from the shell.

Possibly, but intuitive and software often don't go hand in hand. :)


More information about the Python-list mailing list