問題描述:
環(huán)境: CentOS6.4
一個用python寫的監(jiān)控腳本test1.py,用while True方式一直運行,在ssh遠程(使用putty終端)時通過以下命令啟動腳本:
python test1.py &現(xiàn)在腳本正常運行,通過ps能看到進程號,此時直接關閉ssh終端(不是用exit命令,是直接通過putty的關閉按鈕執(zhí)行的), 再次登錄后發(fā)現(xiàn)進程已經(jīng)退出了。
通過后臺啟動的方式該問題已經(jīng)解決,這里總結(jié)下,也方便我以后查閱。
linux環(huán)境下,在c中守護進程是通過fork方式實現(xiàn)的,python也可以通過該方式實現(xiàn),示例代碼如下:
1 #!/usr/bin/env python 2 #E-Mail : Mike_Zhang@live.com 3 import time,platform 4 import os 5 6 def funzioneDemo(): 7 # 這是具體業(yè)務函數(shù)示例 8 fout = open('/tmp/demone.log', 'w') 9 while True:10 fout.write(time.ctime()+'/n')11 fout.flush()12 time.sleep(2)13 fout.close()14 15 def createDaemon():16 # fork進程 17 try:18 if os.fork() > 0: os._exit(0)19 except OSError, error:20 PRint 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)21 os._exit(1) 22 os.chdir('/')23 os.setsid()24 os.umask(0)25 try:26 pid = os.fork()27 if pid > 0:28 print 'Daemon PID %d' % pid29 os._exit(0)30 except OSError, error:31 print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)32 os._exit(1)33 # 重定向標準IO34 sys.stdout.flush()35 sys.stderr.flush()36 si = file("/dev/null", 'r')37 so = file("/dev/null", 'a+')38 se = file("/dev/null", 'a+', 0)39 os.dup2(si.fileno(), sys.stdin.fileno())40 os.dup2(so.fileno(), sys.stdout.fileno())41 os.dup2(se.fileno(), sys.stderr.fileno())42 43 # 在子進程中執(zhí)行代碼44 funzioneDemo() # function demo45 46 if __name__ == '__main__': 47 if platform.system() == "Linux":48 createDaemon()49 else:50 os._exit(0)
可以通過upstart把應用封裝成系統(tǒng)服務,這里直接記錄下完整示例。
1、編寫python腳本
[root@local t27]# cat test123.py#!/usr/bin/env pythonimport os,timewhile True : print time.time() time.sleep(1)2、編寫upstat配置文件
[root@local t27]# cat /etc/init/mikeTest.confdescr3、重新加載upstate
initctl reload-configuration4、啟動服務
[root@local t27]# start mikeTestmikeTest start/running, process 6635[root@local t27]# ps aux | grep test123.pyroot 6635 0.0 0.0 22448 3716 ? Ss 09:55 0:00 python /test/t27/test123.pyroot 6677 0.0 0.0 103212 752 pts/1 S+ 09:56 0:00 grep test123.py5、停止服務
[root@local t27]# stop mikeTestmikeTest stop/waiting[root@local t27]# ps aux | grep test123.pyroot 6696 0.0 0.0 103212 752 pts/1 S+ 09:56 0:00 grep test123.py[root@local t27]#
1、python代碼
[root@local test]# cat test123.py#!/usr/bin/env pythonimport os,timewhile True : print time.time() time.sleep(1)2、編寫啟動腳本
[root@local test]# cat start.sh#! /bin/shpython test123.py &3、啟動進程
[root@local test]#./start.sh如果直接用&啟動進程:
python test123.py &直接關閉ssh終端會導致進程退出。
如果臨時跑程序的話,可以通過screen、tmux啟動程序,這里描述下tmux啟動的方式。
1、啟動tmux
在終端輸入tmux即可啟動2、在tmux中啟動程序
直接執(zhí)行如下命令即可(腳本參考上面的): python test123.py
3、直接關閉ssh終端(比如putty上的關閉按鈕);
4、重新ssh上去之后,執(zhí)行如下命令:
tmux attach現(xiàn)在可以看到python程序還在正常執(zhí)行。
在windows下沒有深入的研究過,我經(jīng)常用的方法是修改python腳本的擴展名為".pyw",雙擊即可后臺運行,不需要修改任何代碼。新聞熱點
疑難解答