Featured post
multithreading - Python multiprocessing and sockets not being closed -
i'm experiencing odd behaviour when using multiprocessing , socket on python. i'm dealing piece of code similar 1 i'm posting below (i've simplified things lot trying naive).
the code spawns 3 processes: 1 process nothing, process launches third one, listening on socket. if terminate "listener" process, socket still remains open (i can see there netstat).
- if remove (or stop) "donothing" process, works.
- if switch threading.thread, works, but
- if leave donothing process , switch server , launcher threading.thread, problem persists.
does have hint why socket still opened? there problem dealing multiprocessing , sockets?
i'm using python 2.6.6 running on linux.
thank much, alvaro.
import time multiprocessing import process, event import socket class server(process): def __init__(self, port): super(server, self).__init__() self.s = socket.socket(socket.af_inet, socket.sock_stream) self.s.bind(("127.0.0.1",port)) self.s.listen(1) self.s.settimeout(10) self.is_stop = event() self.is_stop.clear() def run(self): while not self.is_stop.is_set(): print "server: running (pid %s)" % self.pid time.sleep(1) print "server: exiting" def stop(self): self.is_stop.set() self.s.close() class launcher(process): def __init__(self): super(launcher, self).__init__() self.srv = server(9999) self.srv.start() def run(self): print "launcher pid %s" % self.pid while true: time.sleep(1) def stop(self): print "launcher: i'm stopping server" self.srv.stop() self.srv.terminate() self.srv.join() print "launcher: server stopped" class donothing(process): def __init__(self): super(donothing, self).__init__() def run(self): while true: time.sleep(1) l = launcher() l.start() dn = donothing() dn.start() time.sleep(2) print " stop launcher " l.stop() while true: time.sleep(1)
edit:
relevant netstat -lnp
output:
tcp 0 0 127.0.0.1:9999 0.0.0.0:* listen 7183/python
i've noticed pid shown in netstat changes parent process (when process server running) launcher's 1 (when server stopped).
to fix immediate problem (of socket not shutting down), add self.s.shutdown(socket.shut_rdwr)
server.stop
method:
def stop(self): self.is_stop.set() self.s.shutdown(socket.shut_rdwr) self.s.close()
- Get link
- X
- Other Apps
Comments
Post a Comment