摘要:守護進程(daemon)是指在UNIX或其他多任務操作系統中在後臺執行的電腦程序,並不會接受電腦用戶的直接操控。此類程序會被以進程的形式初始化。守護進程程序的名稱通常以字母“d”結尾:例如,syslogd就是指管理系統日誌的守護進程。(維基百科)
編程原則:在後臺運行(fork) ---- 脫離控制終端(setsid) ---- 禁止進程重新打開控制終端(fork) ---- 切換工作目錄(chdir) ---- 重定向標準輸入/輸出/出錯(dup2) ---- 重設文件創建權限(umask)
Pythone版本:
# -*- coding: utf-8 -*-
''' daemon.py'''
import atexit
import os
import sys
import time
from signal import signal, SIGTERM, SIGKILL
class Daemon(object):
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
self.umask = 0
def daemonize(self):
#後臺運行
try:
pid = os.fork()
if pid > 0:
#脫離shell(脫殼)
sys.exit(0)
except OSError, e:
sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
sys.exit(1)
#脫離控制終端
os.setsid()
#第二次fork,禁止進程重新打開控制終端
try:
pid = os.fork()
if pid > 0:
#脫離第一個子進程
sys.exit(0)
except OSError, e:
sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
sys.exit(1)
#改變當前工作目錄(防止當前工作目錄無法卸載)
os.chdir('/')
#重定向標準輸入/輸出/錯誤
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(), sys.stdin.fileno()) #fileno()返回文件描述符
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
#重設文件創建權限
self.umask = os.umask(0)
#記錄最終孤兒進程ID(第二個子進程)
self.write_pid()
#註冊程序退出時的回調函數
atexit.register(self.delpid)
def write_pid(self):
# write pidfile
if not self.pidfile:
return
pid = str(os.getpid())
try:
os.umask(self.umask)
file(self.pidfile, 'w').write('%s\n' % pid)
except Exception, wpid_err:
sys.stderr.write(u'Error trying to write pid file: %s\n' % wpid_err)
sys.exit(1)
os.umask(0)
atexit.register(self.delpid)
def delpid(self):
try:
os.unlink(self.pidfile)
except OSError as err:
message = 'Error trying to remove PID file: %s\n'
sys.stderr.write(message % err)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = 'pidfile %s already exist. Daemon already running?\n'
sys.stderr.write(message % self.pidfile)
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
sys.stdout.write("%s\n" %pid)
if not pid:
message = 'pidfile %s does not exist. Is the Daemon running?\n'
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
os.kill(pid, SIGKILL)
time.sleep(0.1)
sys.stdout.write("kill %s\n" %pid)
os.unlink(self.pidfile)
except OSError, err:
if err.errno == 3:
if os.path.exists(self.pidfile):
message = "Daemon's not running? removing pid file %s.\n"
sys.stderr.write(message % self.pidfile)
os.remove(self.pidfile)
else:
sys.stderr.write(err.strerror)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
pass
測試用例:#!/usr/bin/env python
'''pydaemo.py'''
import sys, time, os
from daemon import Daemon
class MyDaemon(Daemon):
def run(self):
while True:
time.sleep(1)
if __name__ == "__main__":
A = MyDaemon("/tmp/daemon.pid")
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
A.start()
elif 'stop' == sys.argv[1]:
A.stop()
elif 'restart' == sys.argv[1]:
A.restart()
else:
print "Unknown command"
sys.exit(1)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(1)
C版:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
/**init.c**/
void init_daemon(void)
{
pid_t pid;
int fd;
//後臺運行
if(pid = fork())
exit(0);
else if(pid < 0)
exit(1);
printf("脫離控制終端\n");
setsid();
//禁止進程重新打開控制終端
if(pid = fork())
exit(0);
else if(pid < 0)
exit(1);
printf("切換工作目錄\n");
chdir("/");
fd = open("/dev/null", O_RDWR, 0);
if(fd != -1)
{
printf("重定向標準輸入/輸出/出錯\n");
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if(fd >2)
close(fd);
}
printf("重設文件創建權限\n");
umask(0);
}
//測試
int main(void)
{
init_daemon();
/**以下就是業務代碼**/
while(1)
sleep(1);
return 0;
}
總結:以上是比較傳統的守護進程編程方式,更好的方法是利用dbus來實現交互式的守護進程,比如一個圖形界面程序,通過dbus調用一個後臺程序來採取數據,並可以按需啓動/關閉後臺進程。