1 """A few things that didn't seem to fit anywhere else."""
13 PID_FILE = '/var/run/nm.pid'
15 def as_daemon_thread(run):
16 """Call function <run> with no arguments in its own thread."""
17 thr = threading.Thread(target=run)
21 def close_nonstandard_fds():
22 """Close all open file descriptors other than 0, 1, and 2."""
24 for fd in range(3, os.sysconf(_SC_OPEN_MAX)):
26 except OSError: pass # most likely an fd that isn't open
28 # after http://www.erlenstar.demon.co.uk/unix/faq_2.html
30 """Daemonize the current process."""
31 if os.fork() != 0: os._exit(0)
33 if os.fork() != 0: os._exit(0)
36 devnull = os.open(os.devnull, os.O_RDWR)
37 for fd in range(3): os.dup2(devnull, fd)
39 def fork_as(su, function, *args):
40 """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."""
45 close_nonstandard_fds()
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)
59 """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."""
61 if os.access(PID_FILE, os.F_OK): # check for a pid file
62 handle = open(PID_FILE) # pid file exists, read it
63 other_pid = int(handle.read())
65 # check for a process with that pid by sending signal 0
66 try: os.kill(other_pid, 0)
68 if e.errno == errno.ESRCH: other_pid = None # doesn't exist
69 else: raise # who knows
71 # write a new pid file
72 write_file(PID_FILE, lambda f: f.write(str(os.getpid())))
75 def write_file(filename, do_write, **kw_args):
76 """Write file <filename> atomically by opening a temporary file, using <do_write> to write that file, and then renaming the temporary file."""
77 os.rename(write_temp_file(do_write, **kw_args), filename)
79 def write_temp_file(do_write, mode=None, uidgid=None):
80 fd, temporary_filename = tempfile.mkstemp()
81 if mode: os.chmod(temporary_filename, mode)
82 if uidgid: os.chown(temporary_filename, *uidgid)
83 f = os.fdopen(fd, 'w')
86 return temporary_filename