~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to loggerhead/daemon.py

  • Committer: Michael Hudson
  • Date: 2008-09-12 04:36:13 UTC
  • Revision ID: michael.hudson@canonical.com-20080912043613-d2550i1udbl2g86b
our tests aren't the greatest, but let's keep them passing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# daemon code from ASPN
 
2
#
 
3
 
 
4
import os
 
5
 
 
6
 
 
7
def daemonize(pidfile, home):
 
8
    """
 
9
    Detach this process from the controlling terminal and run it in the
 
10
    background as a daemon.
 
11
    """
 
12
 
 
13
    WORKDIR = "/"
 
14
    REDIRECT_TO = getattr(os, 'devnull', '/dev/null')
 
15
    MAXFD = 1024
 
16
 
 
17
    try:
 
18
        pid = os.fork()
 
19
    except OSError, e:
 
20
        raise Exception("%s [%d]" % (e.strerror, e.errno))
 
21
 
 
22
    if pid == 0:      # The first child.
 
23
        os.setsid()
 
24
 
 
25
        try:
 
26
            pid = os.fork()     # Fork a second child.
 
27
        except OSError, e:
 
28
            raise Exception, "%s [%d]" % (e.strerror, e.errno)
 
29
 
 
30
        if pid == 0:  # The second child.
 
31
            os.chdir(WORKDIR)
 
32
        else:
 
33
            os._exit(0) # Exit parent (the first child) of the second child.
 
34
    else:
 
35
        os._exit(0)     # Exit parent of the first child.
 
36
 
 
37
    import resource            # Resource usage information.
 
38
    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
 
39
    if (maxfd == resource.RLIM_INFINITY):
 
40
        maxfd = MAXFD
 
41
 
 
42
    fd = os.open(REDIRECT_TO, os.O_RDONLY)
 
43
    os.dup2(fd, 0)
 
44
    fd = os.open(REDIRECT_TO, os.O_WRONLY)
 
45
    os.dup2(fd, 1)
 
46
    os.dup2(fd, 2)
 
47
 
 
48
    # Iterate through and close all other file descriptors.
 
49
    for fd in range(3, maxfd):
 
50
        try:
 
51
            os.close(fd)
 
52
        except OSError:        # ERROR, fd wasn't open to begin with (ignored)
 
53
            pass
 
54
 
 
55
    f = open(pidfile, 'w')
 
56
    f.write('%d\n' % (os.getpid(),))
 
57
    f.write('%s\n' % (home,))
 
58
    f.close()
 
59
 
 
60
 
 
61
def is_running(pidfile):
 
62
    try:
 
63
        f = open(pidfile, 'r')
 
64
    except IOError:
 
65
        return False
 
66
    pid = int(f.readline())
 
67
    f.close()
 
68
    try:
 
69
        os.kill(pid, 0)
 
70
    except OSError:
 
71
        # no such process
 
72
        return False
 
73
    return True