-
Notifications
You must be signed in to change notification settings - Fork 626
/
PlexConnect_daemon.py
executable file
·89 lines (68 loc) · 2.18 KB
/
PlexConnect_daemon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python
"""
PlexConnectDaemon
Creates a proper daemon on mac/linux
"""
import os
import sys
import signal
import argparse
import atexit
from PlexConnect import startup, shutdown, run, cmdShutdown
def daemonize(args):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
"""
# Make a non-session-leader child process
try:
pid = os.fork()
if pid != 0:
sys.exit(0)
except OSError, e:
raise RuntimeError("1st fork failed: %s [%d]" % (e.strerror, e.errno))
# decouple from parent environment
os.setsid()
# Make sure I can read my own files and shut out others
prev = os.umask(0)
os.umask(prev and int('077', 8))
# Make the child a session-leader by detaching from the terminal
try:
pid = os.fork()
if pid != 0:
sys.exit(0)
except OSError, e:
raise RuntimeError("2nd fork failed: %s [%d]" % (e.strerror, e.errno))
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
se = file('/dev/null', 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
if args.pidfile:
try:
atexit.register(delpid)
pid = str(os.getpid())
file(args.pidfile, 'w').write("%s\n" % pid)
except IOError, e:
raise SystemExit("Unable to write PID file: %s [%d]" % (e.strerror, e.errno))
def delpid():
global args
os.remove(args.pidfile)
def sighandler_shutdown(signum, frame):
signal.signal(signal.SIGINT, signal.SIG_IGN) # we heard you!
cmdShutdown()
if __name__ == '__main__':
signal.signal(signal.SIGINT, sighandler_shutdown)
signal.signal(signal.SIGTERM, sighandler_shutdown)
parser = argparse.ArgumentParser(description='PlexConnect as daemon.')
parser.add_argument('--pidfile', dest='pidfile')
args = parser.parse_args()
daemonize(args)
running = startup()
while running:
running = run()
shutdown()