add sorting tables to the pcu view.
[monitor.git] / monitor / util / process.py
1 #!/usr/bin/python
2 #
3 # Utility functions
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # $Id: pl_mom.py,v 1.4 2006/06/02 04:00:00 mlhuang Exp $
9 #
10
11 import os
12 import sys
13
14 def writepid(prog):
15     """
16     Check PID file. Exit if already running. Update PID file.
17     """
18
19     try:
20         pidfile = file("/var/run/%s.pid" % prog, "r")
21         pid = pidfile.readline().strip()
22         pidfile.close()
23         if os.path.isdir("/proc/" + pid):
24             print "Error: Another copy of %s is still running (%s)" % (prog, pid)
25             sys.exit(1)
26     except IOError:
27         pass
28
29     pidfile = file("/var/run/%s.pid" % prog, "w")
30     pidfile.write(str(os.getpid()))
31     pidfile.close()
32
33
34 def removepid(prog):
35     os.unlink("/var/run/%s.pid" % prog)
36
37
38 def daemonize():
39     """
40     Daemonize self. Detach from terminal, close all open files, and fork twice.
41     """
42
43     pid = os.fork()
44     if pid == 0:
45         # Detach from terminal
46         os.setsid()
47         # Orphan myself
48         pid = os.fork()
49         if pid == 0:
50             os.chdir("/")
51         else:
52             os._exit(0)
53     else:
54         os._exit(0)
55
56     # Close all open file descriptors
57     import resource
58     maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
59     if (maxfd == resource.RLIM_INFINITY):
60         maxfd = 1024
61     for fd in range(0, maxfd):
62         try:
63             os.close(fd)
64         except OSError:
65             pass
66
67     # Redirect stdin to /dev/null
68     os.open("/dev/null", os.O_RDWR)