Created
June 15, 2012 03:28
-
-
Save rizkyabdilah/2934510 to your computer and use it in GitHub Desktop.
Handle/kill child process when parent process dies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from multiprocessing import Process | |
import os | |
import sys | |
from time import sleep | |
class JobSeeker(object): | |
def __init__(self, ppid=None): | |
self.ppid = ppid | |
def look_for_job(self): | |
while True: | |
# if parent process is no longer valid, kill himself | |
if self.ppid and self.ppid != os.getppid(): | |
sys.exit(2) | |
sleep(10) | |
if __name__ == '__main__': | |
my_pid = os.getpid() | |
worker_number = 4 | |
print "Start master process, PID=%d" % my_pid | |
for pnum in xrange(worker_number): | |
unemployed = JobSeeker(ppid=my_pid) | |
p = Process(target=unemployed.look_for_job) | |
p.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment