~entertainer-releases/entertainer/trunk

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
#!/usr/bin/env python
'''Main backend executable'''

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"
__version__ = "0.1"

import ctypes
import gobject
import os
import sys

from entertainerlib.backend.backend_server import BackendServer

def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
    '''Fork the backend server process'''
    try:
        pid = os.fork()
        if pid  > 0:
            sys.exit(0) # Exit first parent
    except OSError, e:
        sys.stderr.write("First fork failed: (%d) %s\n" %
            (e.errno, e.strerror))
        sys.exit(1)
    # Decouple from parent environment
    os.chdir("/")
    os.umask(0)
    os.setsid()
    # Perform the second fork
    try:
        pid = os.fork()
        if pid  > 0:
            sys.exit(0) # Exit second parent
    except OSError, e:
        sys.stderr.write("Second fork failed: (%d) %s\n" %
            (e.errno, e.strerror))
        sys.exit(1)

    for f in sys.stdout, sys.stderr:
        f.flush()

    si = file(stdin, 'r')
    so = file(stdout, 'a+')
    se = file(stderr, 'a+')
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == "__main__":
    if len(sys.argv) > 1 and (sys.argv[1] == "--help" or sys.argv[1] == "-h"):
        print 'Entertainer backend %s, Copyright (c) %s' % \
            (__version__, __copyright__)
        print ""
        print "Usage:"
        print "    --help               - This help listing"
        print "    --foreground         - Run backend as foreground process"
        sys.exit(0)

    if len(sys.argv) > 1 and sys.argv[1] == "--foreground":
        try:
            backend = BackendServer()
        except KeyboardInterrupt:
            backend.quitBackend()
            sys.exit()
    else:
        print "Entertainer backend starting..."
        libc = ctypes.CDLL('libc.so.6')
        libc.prctl(15, 'EntertainerBackend', 0, 0, 0)
        daemonize()
        backend = BackendServer()