|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +# daemonize.py by Ohad Lutzky <[email protected]> |
| 4 | +# Ported from Brian Clapper's daemonize at |
| 5 | +# http://www.clapper.org/software/daemonize/ |
| 6 | + |
| 7 | +"""Simple daemonization utility based on BSD daemon(3) |
| 8 | +
|
| 9 | +Usage from within python: |
| 10 | +- import daemonize |
| 11 | +- run daemonize.daemon() at the appropriate time |
| 12 | +
|
| 13 | +Usage from the shell: |
| 14 | +daemonize.py [path] [arguments] |
| 15 | +
|
| 16 | +Note that [path] has to be a full path to an executable file |
| 17 | +""" |
| 18 | + |
| 19 | +import os, sys |
| 20 | + |
| 21 | +def daemon(nochdir = False, noclose = False): |
| 22 | + """Daemonizes the current process; this means detaching from the |
| 23 | + controlling terminal and running in the background as a system |
| 24 | + daemon. |
| 25 | +
|
| 26 | + Unless nochdir is set, the current working directory is set to "/". |
| 27 | +
|
| 28 | + Unless noclose is set, standard input, output and error will be |
| 29 | + redirected to /dev/null.""" |
| 30 | + |
| 31 | + def do_fork(): |
| 32 | + if os.fork() != 0: |
| 33 | + # This is the parent, we should exit |
| 34 | + os._exit(0) |
| 35 | + # Note that we don't check the return value of fork - we want to |
| 36 | + # become a child, and upon error, an exception will be thrown |
| 37 | + |
| 38 | + def redirect_fds(): |
| 39 | + os.close(0) |
| 40 | + os.close(1) |
| 41 | + os.close(2) |
| 42 | + |
| 43 | + os.open("/dev/null", os.O_RDWR) |
| 44 | + os.dup(0) |
| 45 | + os.dup(0) |
| 46 | + |
| 47 | + do_fork() |
| 48 | + os.setsid() |
| 49 | + do_fork() |
| 50 | + os.umask(0) |
| 51 | + |
| 52 | + if not nochdir: os.chdir("/") |
| 53 | + if not noclose: redirect_fds() |
| 54 | + |
| 55 | +if __name__ == '__main__': |
| 56 | + daemon(0,0) |
| 57 | + os.execv(sys.argv[1], sys.argv[2:]) |
0 commit comments