Created
May 4, 2017 00:41
-
-
Save pirate/e6779809084b3cb16fe1b724a200091e 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 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