Sunday 15 February 2015

subprocess - Killing child processes created in class __init__ in Python -



subprocess - Killing child processes created in class __init__ in Python -

(new python , oo - apologize in advance if i'm beingness stupid here)

i'm trying define python 3 class such when instance created 2 subprocesses created. these subprocesses work in background (sending , listening udp packets). subprocesses need communicate each other , instance (updating instance attributes based on received udp, among other things).

i creating subprocesses os.fork because don't understand how utilize subprocess module send multiple file descriptors kid processes - maybe part of problem.

the problem running how kill kid processes when instance destroyed. understanding shouldn't utilize destructors in python because stuff should cleaned , garbage collected automatically python. in case, next code leaves children running after exits.

what right approach here?

import os time import sleep class a: def __init__(self): sfp, pts = os.pipe() # senderfromparent, parenttosender pfs, stp = os.pipe() # parentfromsender, sendertoparent pfl, ltp = os.pipe() # parentfromlistener, listenertoparent sfl, lts = os.pipe() # senderfromlistener, listenertosender pid = os.fork() if pid: # parent os.close(sfp) os.close(stp) os.close(lts) os.close(ltp) os.close(sfl) self.pts = os.fdopen(pts, 'w') # allow creator of inst self.pfs = os.fdopen(pfs, 'r') # send , receive messages self.pfl = os.fdopen(pfl, 'r') # to/from sender , else: # listener processes # sender or listener os.close(pts) os.close(pfs) os.close(pfl) pid = os.fork() if pid: # sender os.close(ltp) os.close(lts) sender(self, sfp, stp, sfl) else: # listener os.close(stp) os.close(sfp) os.close(sfl) listener(self, ltp, lts) def sender(a, sfp, stp, sfl): sfp = os.fdopen(sfp, 'r') # receive messages parent stp = os.fdopen(stp, 'w') # send messages parent sfl = os.fdopen(sfl, 'r') # received messages listener while true: # send udp packets based on messages parent , process # responses listener (some responses passed parent) print("sender alive") sleep(1) def listener(a, ltp, lts): ltp = os.fdopen(ltp, 'w') # send messages parent lts = os.fdopen(lts, 'w') # send messages sender while true: # hear , process incoming udp packets, sending # sender , parent print("listener alive") sleep(1) = a()

running above produces:

sender live listener live sender live listener live ...

actually, should utilize destructors. python objects have __del__ method, called before object garbage-collected.

in case, should define

def __del__(self): ...

within class a sends appropriate kill signals kid processes. don't forget store kid pids in parent process, of course.

python subprocess fork kill

No comments:

Post a Comment