Created
July 9, 2011 22:20
-
-
Save taicki/1074004 to your computer and use it in GitHub Desktop.
try to manage child processes in python
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 os | |
import signal | |
import time | |
def main(): | |
commands = [ | |
("python", "sample.py"), | |
("python", "sample.py"), | |
] | |
children = [] | |
for i in commands: | |
pid = os.fork() | |
if pid == 0: | |
# child | |
os.execvp(i[0], i) | |
else: | |
# parent | |
children.append(pid) | |
try: | |
while True: | |
print children | |
time.sleep(1) | |
except KeyboardInterrupt: | |
for c in children: | |
os.kill(c, signal.SIGUSR1) | |
print os.waitpid(c, 0) | |
if __name__ == "__main__": | |
main() |
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 os | |
import signal | |
import time | |
def main(): | |
shutdown = False | |
def sighandler(signum, grame): | |
shutdown = True | |
signal.signal(signal.SIGUSR1, sighandler) | |
pid = os.getpid() | |
i = 0 | |
with open("/tmp/{0}".format(pid), "w") as fp: | |
while True: | |
fp.write("{0}\n".format(i)) | |
fp.flush() | |
if shutdown: | |
break | |
time.sleep(1) | |
i += 1 | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment