source: code/daemon.py @ 133

Last change on this file since 133 was 23, checked in by trishank, 7 years ago

Add pre-release upPIR from June 2011.

File size: 1.3 KB
Line 
1#  Daemon Module - basic facilities for becoming a daemon process
2#
3#  Combines ideas from Steinar Knutsens daemonize.py and
4#  Jeff Kunces demonize.py
5
6# Originally posted to python-list; an archive of the post is available
7# here: http://aspn.activestate.com/ASPN/Mail/Message/python-list/504777
8# Assumed is that the author intended for the (fairly trivial body of) code
9# to be freely usable by any developer.
10
11"""Facilities for Creating Python Daemons"""
12
13import os
14import time
15import sys
16
17
18class NullDevice:
19  def write(self, s):
20    pass
21
22
23def daemonize():
24  """
25  daemonize:
26    Purpose:
27      Detach from stdin/stdout/stderr, return control of the term to the user.
28
29    Returns:
30      Nothing.
31
32  """
33
34  if os.name == "nt" or os.name == "ce":
35    # No way to fork or daemonize on windows. Just do nothing for now?
36    return
37
38  if not os.fork():
39    # get our own session and fixup std[in,out,err]
40    os.setsid()
41    sys.stdin.close()
42    sys.stdout = NullDevice()
43    sys.stderr = NullDevice()
44    if not os.fork():
45      # hang around till adopted by init
46      ppid = os.getppid()
47      while ppid != 1:
48        time.sleep(0.5)
49        ppid = os.getppid()
50    else:
51      # time for child to die
52      os._exit(0)
53  else:
54    # wait for child to die and then bail
55    os.wait()
56    sys.exit()
Note: See TracBrowser for help on using the repository browser.