戲說守護、僵尸、孤兒進程

首先說簡單的結論:

  • 沒有父進程的進程就是孤兒進程,孤兒進程會被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多進程就是這樣, 監控子進程的運行狀態, 當其意外退出時自動重啟子進程。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,363評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,497評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,305評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,962評論 1 311
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,727評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,193評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,257評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,411評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,945評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,777評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,978評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,519評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,216評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,657評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,960評論 2 373

推薦閱讀更多精彩內容

  • 一,守護進程概述Linux Daemon(守護進程)是運行在后臺的一種特殊進程。它獨立于控制終端并且周期性地執行某...
    柏樹_Jeff閱讀 2,969評論 0 5
  • Linux 進程管理與程序開發 進程是Linux事務管理的基本單元,所有的進程均擁有自己獨立的處理環境和系統資源,...
    JamesPeng閱讀 2,483評論 1 14
  • 基本概念 Linux Daemon(守護進程)是運行在后臺的一種特殊進程。它獨立于控制終端并且周期性地執行某種任務...
    lifesmily閱讀 971評論 0 0
  • 端午假期,我來到了向往的草原,到達的那刻發了一個朋友圈:一路北上,我會在這里拍我的花兒、趕我的牛、烤我的全羊、住我...
    曉多閱讀 1,248評論 9 14
  • 請寫出下面幾個alert的執行結果 請寫出以下程序的輸出 一個數組par中存放有多個人員的信息,每個人員的心心由年...
    ps_fba7閱讀 646評論 0 0