Skip to content

Instantly share code, notes, and snippets.

@taicki
Created July 9, 2011 22:20
Show Gist options
  • Save taicki/1074004 to your computer and use it in GitHub Desktop.
Save taicki/1074004 to your computer and use it in GitHub Desktop.
try to manage child processes in python
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()
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