Skip to content

Instantly share code, notes, and snippets.

@nathantypanski
Created February 22, 2015 20:40
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 nathantypanski/81f39bcf462374d995db to your computer and use it in GitHub Desktop.
Save nathantypanski/81f39bcf462374d995db to your computer and use it in GitHub Desktop.
import sys
import os
# maximum file descriptors to close if sysconf(SC_OPEN_MAX)
# is indeterminate
BD_MAX_CLOSE = 8192
def become_daemon(no_umask0=False,
no_chdir=False,
no_close_open_files=False,
no_reopen_standard_fds=False):
try:
pid = os.fork()
if pid == 0:
pass # child falls through
else:
exit(0) # parent terminates
except OSError:
return -1
if os.setsid() == -1: # become the leader of a new session
return -1
try: # ensure we are not session leader
pid = os.fork()
if pid == 0:
pass
else:
exit(0)
except OSError:
return -1
if not no_umask0:
os.umask(0) # clear file mode creation mask
if not no_chdir:
os.chdir('/') # change to root directory
if not no_close_open_files: # close all open files
max_fd = os.sysconf('SC_OPEN_MAX')
if max_fd == -1:
max_fd = BD_MAX_CLOSE
os.closerange(0, max_fd)
if not no_reopen_standard_fds:
try:
os.close(sys.stdin.fileno())
except OSError:
pass
fd = os.open('/dev/null', os.O_RDWR)
os.dup2(sys.stdin.fileno(), sys.stdout.fileno())
os.dup2(sys.stdin.fileno(), sys.stderr.fileno())
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment