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

Jeff McNeil jeff at jmcneil.net
Fri Jul 20 12:02:31 EDT 2007


The open file descriptor/socket shouldn't "move" between processes when you
kill the parent.  When os.system forks, anything you've got open in the
parent will transfer to the child.  Both descriptors reference the same open
port.  Running the same 'ss' and 'cc' code you've supplied behaves like that
on my workstation:

[jeff at marvin ~]$ cat ss.py
import socket
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPSock.bind(('', 12345))

import os
os.system("python cc.py")

[jeff at marvin ~]$ cat cc.py
import time
time.sleep(2036)

Corresponding lsof output when the above code runs shows the following
before killing the parent.

[jeff at marvin ~]$ /usr/sbin/lsof | grep jeff | grep UDP
python    18713      jeff    3u     IPv4      34004              UDP *:italk

python    18714      jeff    3u     IPv4      34004              UDP *:italk



I don't believe FD_CLOEXEC will not stop the child from inheriting your open
file descriptors. Rather, it will ensure they're closed when execl(3) and
friends are called.

-Jeff




On 7/20/07, alf <ask at me.xs4all.nl> 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.
>
> 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.
>
> Thx,
>
> --
> alf
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070720/c728d040/attachment.html>


More information about the Python-list mailing list