8 from config import PID_FILE
12 def as_daemon_thread(run):
13 """Call function <run> with no arguments in its own thread."""
14 thr = threading.Thread(target=run)
19 def close_nonstandard_fds():
20 """Close all open file descriptors other than 0, 1, and 2."""
22 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
24 except OSError: pass # most likely an fd that isn't open
27 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
29 """Daemonize the current process."""
30 if os.fork() != 0: os._exit(0)
32 if os.fork() != 0: os._exit(0)
35 devnull = os.open(os.devnull, os.O_RDWR)
36 for fd in range(3): os.dup2(devnull, fd)
40 """Return a deep copy of obj."""
41 return cPickle.loads(cPickle.dumps(obj, -1))
44 def fork_as(su, function, *args):
45 """fork(), cd / to avoid keeping unused directories open, close all nonstandard file descriptors (to avoid capturing open sockets), fork() again (to avoid zombies) and call <function> with arguments <args> in the grandchild process. If <su> is not None, set our group and user ids appropriately in the child process."""
50 close_nonstandard_fds()
51 pw_ent = pwd.getpwnam(su)
55 if child_pid == 0: function(*args)
57 os.seteuid(os.getuid()) # undo su so we can write the log file
58 os.setegid(os.getgid())
61 else: os.waitpid(child_pid, 0)
65 """We use a pid file to ensure that only one copy of NM is running at a given time. If successful, this function will write a pid file containing the pid of the current process. The return value is the pid of the other running process, or None otherwise."""
67 # check for a pid file
68 if os.access(PID_FILE, os.F_OK):
69 # pid file exists, read it
70 handle = open(PID_FILE)
71 other_pid = int(handle.read())
73 # check for a process with that pid by sending signal 0
74 try: os.kill(other_pid, 0)
76 if e.errno == errno.ESRCH: other_pid = None # doesn't exist
77 else: raise # who knows
79 # write a new pid file
80 write_file(PID_FILE, lambda thefile: thefile.write(str(os.getpid())))
84 def write_file(filename, do_write):
85 """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
86 os.rename(write_temp_file(do_write), filename)
89 def write_temp_file(do_write):
90 fd, temporary_filename = tempfile.mkstemp()
91 thefile = os.fdopen(fd, 'w')
94 return temporary_filename