Package aisutils :: Module daemon
[hide private]
[frames] | no frames]

Source Code for Module aisutils.daemon

 1  #!/usr/bin/env python 
 2  __author__    = 'Kurt Schwehr' 
 3  __version__   = '$Revision: 8506 $'.split()[1] 
 4  __revision__  = __version__ 
 5  __date__      = '$Date: 2008-02-04 15:32:33 -0500 (Mon, 04 Feb 2008) $'.split()[1] 
 6  __copyright__ = '2007, 2008' 
 7  __license__   = 'GPL v2' 
 8  __doc__ = ''' 
 9  Daemon tool to detach from the terminal 
10   
11  @requires: U{epydoc<http://epydoc.sourceforge.net/>} > 3.0alpha3 
12  @status: under development 
13  @since: 2008-Feb-04 
14  @undocumented: __doc__  
15  @todo: Clean way to shut down 
16  ''' 
17   
18  import os 
19   
20 -def stdCmdlineOptions(parser):
21 ''' 22 Standard command line options 23 @param parser: OptionParser parser that will get the additional options 24 ''' 25 26 parser.add_option('-d' 27 ,'--daemon' 28 ,dest='daemon_mode' 29 ,default=False,action='store_true' 30 ,help='Detach from the terminal and run as a daemon service.' 31 +' Returns the pid. [default: %default]') 32 33 # FIX: have an option to make a default pid file location 34 35 parser.add_option('--pid-file' 36 ,dest='pid_file' 37 ,default=None 38 ,help='Where to write the process id when in daemon mode')
39 40
41 -def start(pid_file=None):
42 ''' 43 Jump to daemon mode. Must set either 44 @param options: must have pid_file key 45 ''' 46 create() 47 if pid_file != None: 48 open(pid_file, 'w').write(str(os.getpid())+'\n')
49 50
51 -def create():
52 """ 53 nohup like function to detach from the terminal. Best to call start(), not this. 54 """ 55 56 try: 57 pid = os.fork() 58 except OSError, except_params: 59 raise Exception, "%s [%d]" % (except_params.strerror, except_params.errno) 60 61 if (pid == 0): 62 # The first child. 63 os.setsid() 64 65 try: 66 pid = os.fork() # Fork a second child. 67 except OSError, except_params: 68 raise Exception, "%s [%d]" % (except_params.strerror, except_params.errno) 69 70 if (pid != 0): 71 os._exit(0) # Exit parent (the first child) of the second child. 72 73 else: 74 os._exit(0) # Exit parent of the first child. 75 76 import resource # Resource usage information. 77 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] 78 if (maxfd == resource.RLIM_INFINITY): 79 maxfd = 1024 80 81 # Iterate through and close all file descriptors. 82 if True: 83 for fd in range(0, maxfd): 84 try: 85 os.close(fd) 86 except OSError: # ERROR, fd wasn't open to begin with (ignored) 87 pass 88 89 # Send all output to /dev/null - FIX: send it to a log file 90 os.open('/dev/null', os.O_RDWR) 91 os.dup2(0, 1) 92 os.dup2(0, 2) 93 94 return (0)
95