Skip to content

Instantly share code, notes, and snippets.

@pirate
Created May 4, 2017 00:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirate/e6779809084b3cb16fe1b724a200091e to your computer and use it in GitHub Desktop.
Save pirate/e6779809084b3cb16fe1b724a200091e to your computer and use it in GitHub Desktop.
import os
import sys
def DOUBLE_FORK():
"""Perform a UNIX double-fork to detach, and re attach process to init so it's not a child of web worker"""
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as e:
print("fork #1 failed: %d (%s)" % (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
sys.exit(0)
except OSError as e:
print("fork #2 failed: %d (%s)" % (e.errno, e.strerror))
sys.exit(1)
if __name__ == '__main__':
print('in main process')
DOUBLE_FORK()
print('this running code now has a separate pid, parent of originall process can exit without this being killed')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment