Created
June 6, 2014 06:59
-
-
Save TheWaWaR/e735c917f464911ca4fc to your computer and use it in GitHub Desktop.
UNIX double-fork magic to let process be daemon
This file contains hidden or 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
def spawnDaemon(func): | |
# 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: | |
# parent process, return and keep running | |
return | |
except OSError, e: | |
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) | |
sys.exit(1) | |
os.setsid() | |
# do second fork | |
try: | |
pid = os.fork() | |
if pid > 0: | |
# exit from second parent | |
sys.exit(0) | |
except OSError, e: | |
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) | |
sys.exit(1) | |
# do stuff | |
func() | |
# all done | |
os._exit(os.EX_OK) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment