|
1 import os |
|
2 import sys |
|
3 |
|
4 if os.name == 'posix': |
|
5 def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null'): |
|
6 "Robustly turn into a UNIX daemon, running in our_home_dir." |
|
7 # First fork |
|
8 try: |
|
9 if os.fork() > 0: |
|
10 sys.exit(0) # kill off parent |
|
11 except OSError, e: |
|
12 sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) |
|
13 sys.exit(1) |
|
14 os.setsid() |
|
15 os.chdir(our_home_dir) |
|
16 os.umask(0) |
|
17 |
|
18 # Second fork |
|
19 try: |
|
20 if os.fork() > 0: |
|
21 os._exit(0) |
|
22 except OSError, e: |
|
23 sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)) |
|
24 os._exit(1) |
|
25 |
|
26 si = open('/dev/null', 'r') |
|
27 so = open(out_log, 'a+', 0) |
|
28 se = open(err_log, 'a+', 0) |
|
29 os.dup2(si.fileno(), sys.stdin.fileno()) |
|
30 os.dup2(so.fileno(), sys.stdout.fileno()) |
|
31 os.dup2(se.fileno(), sys.stderr.fileno()) |
|
32 # Set custom file descriptors so that they get proper buffering. |
|
33 sys.stdout, sys.stderr = so, se |
|
34 else: |
|
35 def become_daemon(our_home_dir='.', out_log=None, err_log=None): |
|
36 """ |
|
37 If we're not running under a POSIX system, just simulate the daemon |
|
38 mode by doing redirections and directory changing. |
|
39 """ |
|
40 os.chdir(our_home_dir) |
|
41 os.umask(0) |
|
42 sys.stdin.close() |
|
43 sys.stdout.close() |
|
44 sys.stderr.close() |
|
45 if err_log: |
|
46 sys.stderr = open(err_log, 'a', 0) |
|
47 else: |
|
48 sys.stderr = NullDevice() |
|
49 if out_log: |
|
50 sys.stdout = open(out_log, 'a', 0) |
|
51 else: |
|
52 sys.stdout = NullDevice() |
|
53 |
|
54 class NullDevice: |
|
55 "A writeable object that writes to nowhere -- like /dev/null." |
|
56 def write(self, s): |
|
57 pass |