[转] 使用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内核学习笔记]
目录
[隐藏]
1 字符设备驱动知识讲解
1.1 描述字符设备基本结构体
1.2 作用
1.3 各字段详解
1.4 操作
1.5 实例
1.5.1 代码
1.5.2 运行
[编辑]字符设备驱动知识讲解
作者:[牛涛]
[编辑]描述字符设备基本结构体
/linux/ ......
嗅探器(sniffer)在网络安全领域是一把双刃剑,一方面常被黑客作为网络攻击工具,从
而造成密码被盗、敏感数据被窃等安全事件;另一方面又在协助网络管理员监测网络状况、诊断网络故障、排除网络隐患等方面有着不可替代的作用。嗅探器是企业
必不可少的网络管理工具。本文以Linux平台下三个常用的网络嗅探器Tcpdump、Eth ......
最近在做samsung
s3c2416
在linux下的spi驱动程序,测试了下samsung发布的spi的内核源代码,无论是采用dma或者非dma模式都无法工作。阅读该驱动代码,发现
这码应该是一个未完成的版本,存在很多的bug。于是在这个版本的基础上进行修改,重写一个可用的、支持全双工的通讯 ......