Last active
August 29, 2015 14:04
-
-
Save martinhynar/29da5029d6bf2e313a60 to your computer and use it in GitHub Desktop.
This file contains 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
import multiprocessing | |
import time | |
import os | |
class PMonitor(multiprocessing.Process): | |
def __init__(self, process_id): | |
super(PMonitor, self).__init__() | |
self.process_id = str(process_id) | |
self.semaphore = multiprocessing.Event() | |
def red_light(self): | |
self.semaphore.set() | |
def run(self): | |
try: | |
procdir = os.path.join('/proc', self.process_id) | |
while not self.semaphore.is_set() and os.path.exists(procdir): | |
print '[{0}] Working in child'.format(self.process_id) | |
time.sleep(2) | |
except KeyboardInterrupt, CalledProcessError: | |
pass | |
finally: | |
print '[{0}] Cleanup'.format(self.process_id) | |
if __name__ == '__main__': | |
monitors = {} | |
try: | |
while True: | |
print "[Master] Scanning what I need to scan and span a new subprocess when necessary" | |
# Get the pid of interresting process | |
pid = 1 | |
if not pid in monitors: | |
monitor = PMonitor(pid) | |
monitors[pid] = monitor | |
monitor.start() | |
time.sleep(2) | |
except KeyboardInterrupt: | |
# Don't die immediatelly. Signalize to subprocesses and wait until they all finnish their work | |
print "[Master] Finishing children" | |
for monitor in monitors: | |
monitors[monitor].red_light() | |
# Join subprocess. This will block until subprocess dies | |
monitors[monitor].join() | |
print "[Master] All children terminated, exiting." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment