subprocess (spawned by os.system) inherits open TCP/UDP/IP port
Jeff McNeil
jeff at jmcneil.net
Thu Jul 19 22:31:49 EDT 2007
What's unexpected about it? Child processes inherit all of the open file
descriptors of their parent. A socket is simply another open file
descriptor. When your parent process exits, your child still holds a valid,
open file descriptor.
import sys
import socket
import os
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
s.bind(('', 8888))
pid = os.fork()
if pid > 0:
time.sleep(100)
elif pid == 0:
time.sleep(100)
$ lsof | grep python | grep jeff | grep 8888
python 13048 jeff 3u IPv4 212689 UDP
*:8888
python 13049 jeff 3u IPv4 212689 UDP
*:8888
-Jeff
On 7/19/07, alf <ask at me.xs4all.nl> wrote:
>
>
> Hi,
>
> I need a help with explaining following behavior. Although it is not
> python issue per say, python helped me to write sample programs and
> originally I encountered the issue using python software. So let's
> assume we have two following programs:
>
>
>
> [myhost] ~> cat ss.py
> import socket
> UDPSock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> UDPSock.bind(("",12345))
> import os
> os.system('python cc.py')
>
> [myhost] ~> cat cc.py
> import time
> time.sleep(2036)
>
>
>
> then I start master one, do ctrl-Z and bg.
>
> [myhost] ~> python ss.py
>
> Suspended
> [myhost] ~> bg
> [1] python ss.py &
> [myhost] ~> ps
> UID PID PPID C STIME TTY TIME CMD
> myuser00 3192 3189 0 14:57 pts/0 00:00:00 -tcsh
> myuser00 3247 3192 0 14:57 pts/0 00:00:00 python ss.py
> myuser00 3248 3247 0 14:57 pts/0 00:00:00 python cc.py
>
>
>
> [myhost] ~> netstat -uanp |grep 12345
> (Not all processes could be identified, non-owned process info
> will not be shown, you would have to be root to see it all.)
> udp 0 0 0.0.0.0:12345 0.0.0.0:*
> 3247/python
>
>
>
> As expected netstat indicates process 3247 having port allocated. Then I
> kill the master process and interestingly the child inherits the port
> open.
>
>
> [myhost] ~> kill 3247
> [myhost] ~> netstat -uanp | grep 12345
> (Not all processes could be identified, non-owned process info
> will not be shown, you would have to be root to see it all.)
> udp 0 0 0.0.0.0:12345 0.0.0.0:*
> 3248/python
> [1] + Terminated python ss.py
>
>
>
> Why it is happening? I know that os.system uses fork, but still this is
> something unexpected.
>
>
> 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/20070719/2c8aecfb/attachment.html>
More information about the Python-list
mailing list