[转] 使用Python写Linux的守护进程(daemon)
A simple unix/linux daemon in Python
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
by Sander Marechal
I've
written a simple Python class for creating daemons on unix/linux
systems. It was pieced together for various other examples, mostly
corrections to various Python Cookbook
articles and a couple of examples posted to the Python mailing lists.
It has support for a pidfile to keep track of the process. I hope it's
useful to someone.
Below is the Daemon class. To use it, simply subclass it and implement the run() method.
import sys, os, time, atexit
from signal import SIGTERM
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile
def daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sy
相关文档:
近日,在LinuxCON 2009大会上,桌面 Linux 又成为业界关注的焦点之一。各种不同的声音,嗓门都很大。在这纷纷嚷嚷的氛围中, Linux 如何走出桌面困境?
纵观全局,普及桌面 Linux 的最大障碍之一是系统安装的操作困难性。预装 Windows 已成大 ......
我们说一下Linux中的init命令
Init是Linux操作系统中不可缺少的程序之一。init进程是Linux内核引导运行的,是系统中的第一个进程,其进程号(PID)永远为1。你可以通过#ps -ef|head来查看进程命令。
1) 几个常用的命令
查看系统进程命令:#ps -ef|head
&n ......
-----------------------------------------------------------
#!/bin/bash
#
# Startup script for the tomcat
#
# chkconfig: 345 95 15
# description: tomcat service script
#
# Source function library.
. /etc/rc.d/init.d/functions
TOMCAT_HOME=/home/tomcat
RETVAL=0
checkjava(){
if [ -z "$JAVA ......
Linux 文件系统概述
作者:北南南北
来自:LinuxSir.Org
摘要: 本文通过文件系统的定义说起,然后通过引文简单的介绍了一下文件系统类型;对Linux常用的ext2、ext3及reiserfs 根据本人使用经验也泛泛的谈了谈,但并不是专业的。如何阅读本文,还是用马克思理论告诉我们的方法:一分为二,边看边批吧;
目录索引
一 ......