Skip to content

Instantly share code, notes, and snippets.

@TheWaWaR
Created June 6, 2014 06:59
Show Gist options
  • Save TheWaWaR/e735c917f464911ca4fc to your computer and use it in GitHub Desktop.
Save TheWaWaR/e735c917f464911ca4fc to your computer and use it in GitHub Desktop.
UNIX double-fork magic to let process be daemon
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