Revision: 4515 Author: btongminh Date: 2007-11-08 12:56:01 +0000 (Thu, 08 Nov 2007)
Log Message: ----------- Add daemonize code
Modified Paths: -------------- trunk/pywikipedia/wikipedia.py
Added Paths: ----------- trunk/pywikipedia/daemonize.py
Added: trunk/pywikipedia/daemonize.py =================================================================== --- trunk/pywikipedia/daemonize.py (rev 0) +++ trunk/pywikipedia/daemonize.py 2007-11-08 12:56:01 UTC (rev 4515) @@ -0,0 +1,52 @@ +import sys, os + +__version__ = '$Id: $' + +is_daemon = False + +def daemonize(close_fd = True, chdir = True, write_pid = False, redirect_std = None): + """ Daemonize the current process. Only works on POSIX compatible operating + systems. The process will fork to the background and return control to + the terminal. + + Arguments: + - close_fd: Close the standard streams and replace them by /dev/null + - chdir: Change the current working directory to / + - write_pid: Write the pid to sys.argv[0] + '.pid' + - redirect_std: Filename to redirect stdout and stdin to + """ + + # Fork away + if not os.fork(): + # Become session leader + os.setsid() + # Fork again to prevent the process from acquiring a + # controlling terminal + pid = os.fork() + if not pid: + global is_daemon + is_daemon = True + + if close_fd: + os.close(0) + os.close(1) + os.close(2) + os.open('/dev/null', os.O_RDWR) + if redirect_std: + os.open(redirect_std, os.O_RDONLY | os.O_APPEND) + else: + os.dup2(0, 1) + os.dup2(1, 2) + if chdir: + os.chdir('/') + return + else: + # Write out the pid + f = open(sys.argv[0] + '.pid', 'w') + f.write(str(pid)) + f.close() + os._exit(0) + else: + # Exit to return control to the terminal + # os._exit to prevent the cleanup to run + os._exit(0) \ No newline at end of file
Property changes on: trunk/pywikipedia/daemonize.py ___________________________________________________________________ Name: svn:eol-style + native
Modified: trunk/pywikipedia/wikipedia.py =================================================================== --- trunk/pywikipedia/wikipedia.py 2007-11-08 12:50:25 UTC (rev 4514) +++ trunk/pywikipedia/wikipedia.py 2007-11-08 12:56:01 UTC (rev 4515) @@ -5000,6 +5000,12 @@ output(u'Pywikipediabot %s' % (version.getversion())) output(u'Python %s' % (sys.version)) verbose += 1 + elif arg == '-daemonize': + import daemonize + daemonize.daemonize() + elif arg.startswith('-daemonize:'): + import daemonize + daemonize.daemonize(redirect_std = arg[11:]) else: # the argument is not global. Let the specific bot script care # about it. @@ -5377,6 +5383,10 @@ wikipedia, wiktionary, wikitravel, ... This will override the configuration in user-config.py.
+-daemonize:xyz Immediately returns control to the terminal and redirects + stdout and stderr to xyz (only use for bots that require + no input from stdin). + -help Shows this help text.
-log Enable the logfile. Logs will be stored in the logs
pywikipedia-l@lists.wikimedia.org