Skip to content

Instantly share code, notes, and snippets.

@ionelmc
Created February 26, 2013 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ionelmc/5038117 to your computer and use it in GitHub Desktop.
Save ionelmc/5038117 to your computer and use it in GitHub Desktop.
Very simple daemonization code (double-fork, fds close, in/out/err reopen)
#!/usr/bin/python
# based on: http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
from subprocess import call
import os
import sys
import signal
import resource
if hasattr(os, "devnull"):
DEVNULL = os.devnull
else:
DEVNULL = "/dev/null"
def setup_daemon(cwd="/", stdin=DEVNULL, stderr=DEVNULL, stdout=DEVNULL, umask=0):
pid = os.fork()
if pid == 0:
os.setsid() # make it session leader
signal.signal(signal.SIGHUP, signal.SIG_IGN)
pid = os.fork()
if pid == 0:
os.chdir(cwd)
os.umask(umask) # don't inherit file creation perms from parent
else:
os._exit(0) # no atexit and fd flush/close
else:
os._exit(0) # no atexit and fd flush/close
if os.sysconf_names.has_key("SC_OPEN_MAX"):
MAXFD = os.sysconf("SC_OPEN_MAX")
else:
MAXFD = 1024
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY:
maxfd = MAXFD
os.closerange(0, maxfd)
# Redirect the standard I/O file descriptors to the specified file. Since
# the daemon has no controlling terminal, most daemons redirect stdin,
# stdout, and stderr to /dev/null. This is done to prevent side-effects
# from reads and writes to the standard I/O file descriptors.
# This call to open is guaranteed to return the lowest file descriptor,
# which will be 0 (stdin), since it was closed above.
os.open(stdin, os.O_RDWR) # standard input (0)
os.open(stdout, os.O_WRONLY|os.O_TRUNC|os.O_CREAT) # standard output (1)
os.open(stderr, os.O_WRONLY|os.O_TRUNC|os.O_CREAT) # standard error (2)
if __name__ == "__main__":
cwd = os.getcwd()
setup_daemon(
cwd=cwd,
stderr="foo.stderr",
stdout="foo.stdout",
umask=0113, # equiv to "u-x g-x o-wx"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment