首先說簡單的結論:
沒有父進程的進程就是孤兒進程,孤兒進程會被init領養,成為一個準守護進程。
如果進程他爹活著,但是不給子進程收尸(wait、waitpid),子進程就會變成僵尸。
守護進程(Daemon)是在一類脫離終端在后臺執行的程序, 通常以 d 結尾, 隨系統啟動, 其父進程 (ppid) 通常是 init 進程
以下是Wikipedia中關于Daemon的定義:
In multitasking computer operating systems, a daemon (/?di?m?n/ or /?de?m?n/) is a computer program that runs as a background process, rather than being under the direct control of an interactive user. Traditionally daemon names end with the letter d: for example, syslogd is the daemon that implements the system logging facility and sshd is a daemon that services incoming SSH connections.
一般要讓當前程序以守護進程形式運行, 在命令后加 & 并重定向輸出即可:
$ nohup some_program > /dev/null 2>&1 &
這是直接運行程序的方式, 如果是用具體語言代碼的形式來實現呢, 總的來說守護進程應該有以下幾個特征:
- 后臺運行
- 也就是不占用console的前面,也就是bash里運行程序后面加個&
- 成為process group leader
- Process Group Leader就是父進程是init的那個進程。
- 成為session leader
- 一個ssh登錄會啟動一個bash,bash會fork出很多子進程,這些進程輪流接手tty輸出。這都是屬于一個session。 session leader就是這一堆進程的父進程。
- fork一次或者兩次
- fork 兩次是出于被當成庫調用的考慮。
- chdir到/
- 防止占用別的路徑的working dir的fd,導致一些block不能unmount
- umask
- 需要重置umask,防止后續子進程繼承非默認umask造成奇怪的行為。
- 處理標準輸入輸出,錯誤輸出(0,1,2)
- 重定向stdout、stderr、stdin,防止tty中斷后的broken pipe信號。
- 日志
- 輸出重定向后,需要有辦法反映內部情況。
- 信號處理
- 最后最好對將一些終端相關的信號處理忽略一下,防止受到相關信號導致的進程退出。例如:SIGHUP、SIGTTIN、SIGTTOU。這是很多沒有經驗的菜鳥容易忽略的點。一般nohup命令會幫我們處理。
用下面的代碼就可以實現一個非常規范的守護進程(代碼注釋很詳細但有點長):
#!/usr/bin/env python
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='nbMon.pid', stdin='/dev/null', stdout='nbMon.log', stderr='nbMon.log'):
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(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
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
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""
可以看一個示例:
#!/usr/bin/env python
# coding=utf-8
from daemon import Daemon
import socket
import time
html = """HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nConnection: close\r\nContent-Length: """
html404 = """HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: 13\r\n\r\n<h1>404 </h1>"""
class agentD(Daemon):
def run(self):
listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
listen_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_fd.bind(("0.0.0.0", 9000))
listen_fd.listen(10)
while True:
conn, addr = listen_fd.accept()
print "coming", conn, addr
read_data = conn.recv(10000)
#print read_data
try:
pic_name = read_data.split(" ")[1][1:]
print pic_name
with file(pic_name) as f:
pic_content = f.read()
length = len(pic_content)
html_resp = html
html_resp += "%d\r\n\r\n" % (length)
print html_resp
html_resp += pic_content
except:
print "404 occur"
html_resp = html404
while len(html_resp) > 0:
sent_cnt = conn.send(html_resp)
print "sent:", sent_cnt
html_resp = html_resp[sent_cnt:]
conn.close()
if __name__ == "__main__":
agentd = agentD(pidfile="agentd.pid", stdout="agentd.log", stderr="agentd.log")
agentd.run()
實現了一個非常蹩腳的HTTP Server :-P
上面守護進程的生成步驟中涉及到了孤兒進程:任何孤兒進程產生時都會立即為系統進程init自動接收為子進程,這一過程也被稱為“收養”。但由于創建該進程的進程已不存在,所以仍應稱之為“孤兒進程(Orphan Process)”。
與之相關的一個概念就是 僵尸進程(Zombie Process)了。當子進程退出時, 父進程需要wait/waitpid系統調用來讀取子進程的exit status, 然后子進程被系統回收。如果父進程沒有wait的話, 子進程將變成一個"僵尸進程", 內核會釋放這個子進程所有的資源,包括打開的文件占用的內存等。但在進程表中仍然有一個PCB, 記錄進程號和退出狀態等信息, 并導致進程號一直被占用, 而系統能使用的進程號數量是有限的(可以用ulimit查看相關限制), 如果產生大量僵尸進程的話, 將因為沒有可用的進程號而導致系統不能產生新的進程。
因此很多自帶重啟功能的服務實現就是用wait/waitpid實現的。waitpid()會暫時停止目前進程的執行,直到有信號來到或子進程結束。比如tornado中fork多進程就是這樣, 監控子進程的運行狀態, 當其意外退出時自動重啟子進程。