8 from config import PID_FILE
12 def as_daemon_thread(run):
13 thr = threading.Thread(target=run)
18 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
20 """Daemonize the current process."""
21 if os.fork() != 0: os._exit(0)
23 if os.fork() != 0: os._exit(0)
26 devnull = os.open(os.devnull, os.O_RDWR)
27 for fd in range(3): os.dup2(devnull, fd)
31 """Return a deep copy of obj."""
32 return cPickle.loads(cPickle.dumps(obj, -1))
35 def fork_as(su, function, *args):
36 """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."""
41 # close all nonstandard file descriptors
43 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
45 except OSError: pass # most likely an fd that isn't open
46 pw_ent = pwd.getpwnam(su)
50 if child_pid == 0: function(*args)
52 os.seteuid(os.getuid()) # undo su so we can write the log file
53 os.setegid(os.getgid())
56 else: os.waitpid(child_pid, 0)
60 """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."""
62 # check for a pid file
63 if os.access(PID_FILE, os.F_OK):
64 # pid file exists, read it
65 handle = open(PID_FILE)
66 other_pid = int(handle.read())
68 # check for a process with that pid by sending signal 0
69 try: os.kill(other_pid, 0)
71 if e.errno == errno.ESRCH: other_pid = None # doesn't exist
72 else: raise # who knows
74 # write a new pid file
75 write_file(PID_FILE, lambda thefile: thefile.write(str(os.getpid())))
79 def write_file(filename, do_write):
80 """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
81 os.rename(write_temp_file(do_write), filename)
84 def write_temp_file(do_write):
85 fd, temporary_filename = tempfile.mkstemp()
86 thefile = os.fdopen(fd, 'w')
89 return temporary_filename