~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to loggerhead/daemon.py

  • Committer: Max Bowsher
  • Date: 2011-03-10 14:22:12 UTC
  • mto: This revision was merged to the branch mainline in revision 432.
  • Revision ID: maxb@f2s.com-20110310142212-7xp32hm90lq7zz0d
Remove more things related to the removed code.

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.close()
 
58
 
 
59
 
 
60
def is_running(pidfile):
 
61
    try:
 
62
        f = open(pidfile, 'r')
 
63
    except IOError:
 
64
        return False
 
65
    pid = int(f.readline())
 
66
    f.close()
 
67
    try:
 
68
        os.kill(pid, 0)
 
69
    except OSError:
 
70
        # no such process
 
71
        return False
 
72
    return True