手上有一支用 Python 寫的監控腳本 test1.py,以 while True 的方式持續輪詢。過去我都是從 PuTTY 登入 CentOS 6.4,然後下指令把它丟到背景:
python test1.py &
用 ps 查得到 PID,看起來一切正常。但只要直接按下 PuTTY 的關閉按鈕(不是用 exit 正常登出),重新登入後就會發現進程已經消失。
原因並不難理解:關閉 SSH 連線時,session 的 controlling terminal 消失,kernel 會把 SIGHUP 送給該 session 裡的每一個進程,而這些進程預設的處理方式就是終止。& 只解決了「不佔用前景」的問題,並沒有解決「不被挂断」的問題。
下面把幾種可行的做法記錄下來,之後翻閱方便。
Linux 底下 C 語言的 daemon 是靠 fork 實作的,Python 有 os.fork(),邏輯可以完整照搬。標準流程是:第一次 fork 後父進程立刻退出、呼叫 setsid() 脫離控制終端、第二次 fork 確保不是 session leader、把標準輸入輸出重定向到 /dev/null,最後才進入真正的業務邏輯。
#!/usr/bin/env python
#E-Mail : Mike_Zhang@live.com
import time,platform
import os
def funzioneDemo():
# 這是具體業務函數示例
fout = open('/tmp/demone.log', 'w')
while True:
fout.write(time.ctime()+'\n')
fout.flush()
time.sleep(2)
fout.close()
def createDaemon():
# fork進程
try:
if os.fork() > 0: os._exit(0)
except OSError, error:
print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)
os._exit(1)
os.chdir('/')
os.setsid()
os.umask(0)
try:
pid = os.fork()
if pid > 0:
print 'Daemon PID %d' % pid
os._exit(0)
except OSError, error:
print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)
os._exit(1)
# 重定向標准IO
sys.stdout.flush()
sys.stderr.flush()
si = file("/dev/null", 'r')
so = file("/dev/null", 'a+')
se = file("/dev/null", 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# 在子進程中執行代碼
funzioneDemo() # function demo
if __name__ == '__main__':
if platform.system() == "Linux":
createDaemon()
else:
os._exit(0)
這份範例是 Python 2 語法(print 陳述句、except OSError, error)。若要在 Python 3 上使用,需要改寫成 print() 函式與 except OSError as error,並把 file() 換成 open()。
把應用包成系統服務是最省心的方式,程序掛了還能自動重啟。以下是一份可直接照抄的完整範例。
[root@local t27]# cat test123.py
#!/usr/bin/env python
import os,time
while True :
print time.time()
time.sleep(1)
[root@local t27]# cat /etc/init/mikeTest.conf description "My test" author "Mike_Zhang@live.com" start on runlevel [234] stop on runlevel [0156] chdir /test/t27 exec /test/t27/test123.py respawn
respawn 是關鍵字,進程異常退出時 upstart 會把它拉回來。
initctl reload-configuration
[root@local t27]# start mikeTest mikeTest start/running, process 6635 [root@local t27]# ps aux | grep test123.py root 6635 0.0 0.0 22448 3716 ? Ss 09:55 0:00 python /test/t27/test123.py root 6677 0.0 0.0 103212 752 pts/1 S+ 09:56 0:00 grep test123.py
注意 TTY 一欄是 ?,代表已經完全脫離終端。
[root@local t27]# stop mikeTest mikeTest stop/waiting [root@local t27]# ps aux | grep test123.py root 6696 0.0 0.0 103212 752 pts/1 S+ 09:56 0:00 grep test123.py
[root@local test]# cat test123.py
#!/usr/bin/env python
import os,time
while True :
print time.time()
time.sleep(1)
[root@local test]# cat start.sh #! /bin/sh python test123.py &
[root@local test]# ./start.sh
若直接下 python test123.py &,關掉 SSH 一樣會讓進程跟著走;透過 nohup 或 setsid 包裝則可以避開 SIGHUP。
如果只是臨時跑一陣子,用 tmux 最輕巧:
1. 在終端輸入 tmux 建立 session。
2. 在 tmux 裡直接執行 python test123.py。
3. 直接關掉 SSH 視窗。
4. 重新登入後執行 tmux attach,會看到程式仍在原地輸出。
screen 的用法類似(screen -S name 建立、screen -r name 重連),差別主要在操作快捷鍵與分割窗格體驗。
Windows 我沒有深入研究,常用的土辦法是直接把副檔名改成 .pyw,雙擊即以無主控台視窗的方式執行,不需要改任何一行程式碼。
延伸閱讀:
Python:在指定目錄下查找滿足條件的檔案 https://www.linuxidc.com/Linux/2015-08/121283.htm
Python2.7.7 源碼分析 https://www.linuxidc.com/Linux/2015-08/121168.htm
無需操作系統直接運行 Python 代碼 https://www.linuxidc.com/Linux/2015-05/117357.htm
CentOS 上源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm
Python 腳本獲取 Linux 系統資訊 https://www.linuxidc.com/Linux/2013-08/88531.htm