Skip to content

Instantly share code, notes, and snippets.

@pcn
Created May 19, 2013 23:41
Show Gist options
  • Select an option

  • Save pcn/5609586 to your computer and use it in GitHub Desktop.

Select an option

Save pcn/5609586 to your computer and use it in GitHub Desktop.
An example of playing with fork+exec in python. Basically, when there's a non-zero exit, we can format the output nicely. Otherwise, the parent and child exist in the same process group, tty, etc. so the user is just interacting with the child
#!/usr/bin/env python
# Just a quick demonstration of using fork+exec and watching the exit
# status of the sub-command to demonstrate that this will work with kcs
import sys
import os
import select
import signal
def handle_child(cmdline):
os.execvp(cmdline[0], cmdline)
def simple_fork(cmdline):
def handle_parent_simple(cmdline):
pid, status = os.wait()
if status != 0:
sys.stderr.write("\nPID {0} exited {1} trying to execute:\n {2}\n".format(pid, status, cmdline))
sys.exit(status)
pid = os.fork()
if pid != 0: # parent
handle_parent_simple(cmdline)
else:
handle_child(cmdline)
def main(args = sys.argv):
simple_fork(sys.argv[1:])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment