Python實例淺談之五Python守護進程和腳本單例運行


一、簡介

     守護進程最重要的特性是后台運行;它必須與其運行前的環境隔離開來,這些環境包括未關閉的文件描述符、控制終端、會話和進程組、工作目錄以及文件創建掩碼等;它可以在系統啟動時從啟動腳本/etc/rc.d中啟動,可以由inetd守護進程啟動,也可以有作業規划進程crond啟動,還可以由用戶終端(通常是shell)執行。
       Python有時需要保證只運行一個腳本實例,以避免數據的沖突。 

二、Python守護進程

1、函數實現

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import sys, os  
  4.   
  5. '''將當前進程fork為一個守護進程  
  6.    注意:如果你的守護進程是由inetd啟動的,不要這樣做!inetd完成了  
  7.    所有需要做的事情,包括重定向標准文件描述符,需要做的事情只有chdir()和umask()了  
  8. '''  
  9.   
  10. def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):  
  11.      #重定向標准文件描述符(默認情況下定向到/dev/null)  
  12.     try:   
  13.         pid = os.fork()   
  14.           #父進程(會話組頭領進程)退出,這意味着一個非會話組頭領進程永遠不能重新獲得控制終端。  
  15.         if pid > 0:  
  16.             sys.exit(0)   #父進程退出  
  17.     except OSError, e:   
  18.         sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )  
  19.         sys.exit(1)  
  20.   
  21.      #從母體環境脫離  
  22.     os.chdir("/")  #chdir確認進程不保持任何目錄於使用狀態,否則不能umount一個文件系統。也可以改變到對於守護程序運行重要的文件所在目錄  
  23.     os.umask(0)    #調用umask(0)以便擁有對於寫的任何東西的完全控制,因為有時不知道繼承了什么樣的umask。  
  24.     os.setsid()    #setsid調用成功后,進程成為新的會話組長和新的進程組長,並與原來的登錄會話和進程組脫離。  
  25.   
  26.      #執行第二次fork  
  27.     try:   
  28.         pid = os.fork()   
  29.         if pid > 0:  
  30.             sys.exit(0)   #第二個父進程退出  
  31.     except OSError, e:   
  32.         sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )  
  33.         sys.exit(1)  
  34.   
  35.      #進程已經是守護進程了,重定向標准文件描述符  
  36.   
  37.     for f in sys.stdout, sys.stderr: f.flush()  
  38.     si = open(stdin, 'r')  
  39.     so = open(stdout, 'a+')  
  40.     se = open(stderr, 'a+', 0)  
  41.     os.dup2(si.fileno(), sys.stdin.fileno())    #dup2函數原子化關閉和復制文件描述符  
  42.     os.dup2(so.fileno(), sys.stdout.fileno())  
  43.     os.dup2(se.fileno(), sys.stderr.fileno())  
  44.   
  45. #示例函數:每秒打印一個數字和時間戳  
  46. def main():  
  47.     import time  
  48.     sys.stdout.write('Daemon started with pid %d\n' % os.getpid())  
  49.     sys.stdout.write('Daemon stdout output\n')  
  50.     sys.stderr.write('Daemon stderr output\n')  
  51.     c = 0  
  52.     while True:  
  53.         sys.stdout.write('%d: %s\n' %(c, time.ctime()))  
  54.         sys.stdout.flush()  
  55.         c = c+1  
  56.         time.sleep(1)  
  57.   
  58. if __name__ == "__main__":  
  59.       daemonize('/dev/null','/tmp/daemon_stdout.log','/tmp/daemon_error.log')  
  60.       main()  

        可以通過命令ps -ef | grep daemon.py查看后台運行的繼承,在/tmp/daemon_error.log會記錄錯誤運行日志,在/tmp/daemon_stdout.log會記錄標准輸出日志。

2、類實現

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3.   
  4. #python模擬linux的守護進程  
  5.   
  6. import sys, os, time, atexit, string  
  7. from signal import SIGTERM  
  8.   
  9. class Daemon:  
  10.   def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):  
  11.       #需要獲取調試信息,改為stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr',以root身份運行。  
  12.     self.stdin = stdin  
  13.     self.stdout = stdout  
  14.     self.stderr = stderr  
  15.     self.pidfile = pidfile  
  16.     
  17.   def _daemonize(self):  
  18.     try:  
  19.       pid = os.fork()    #第一次fork,生成子進程,脫離父進程  
  20.       if pid > 0:  
  21.         sys.exit(0)      #退出主進程  
  22.     except OSError, e:  
  23.       sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))  
  24.       sys.exit(1)  
  25.     
  26.     os.chdir("/")      #修改工作目錄  
  27.     os.setsid()        #設置新的會話連接  
  28.     os.umask(0)        #重新設置文件創建權限  
  29.     
  30.     try:  
  31.       pid = os.fork() #第二次fork,禁止進程打開終端  
  32.       if pid > 0:  
  33.         sys.exit(0)  
  34.     except OSError, e:  
  35.       sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))  
  36.       sys.exit(1)  
  37.     
  38.      #重定向文件描述符  
  39.     sys.stdout.flush()  
  40.     sys.stderr.flush()  
  41.     si = file(self.stdin, 'r')  
  42.     so = file(self.stdout, 'a+')  
  43.     se = file(self.stderr, 'a+', 0)  
  44.     os.dup2(si.fileno(), sys.stdin.fileno())  
  45.     os.dup2(so.fileno(), sys.stdout.fileno())  
  46.     os.dup2(se.fileno(), sys.stderr.fileno())  
  47.     
  48.      #注冊退出函數,根據文件pid判斷是否存在進程  
  49.     atexit.register(self.delpid)  
  50.     pid = str(os.getpid())  
  51.     file(self.pidfile,'w+').write('%s\n' % pid)  
  52.     
  53.   def delpid(self):  
  54.     os.remove(self.pidfile)  
  55.   
  56.   def start(self):  
  57.      #檢查pid文件是否存在以探測是否存在進程  
  58.     try:  
  59.       pf = file(self.pidfile,'r')  
  60.       pid = int(pf.read().strip())  
  61.       pf.close()  
  62.     except IOError:  
  63.       pid = None  
  64.     
  65.     if pid:  
  66.       message = 'pidfile %s already exist. Daemon already running!\n'  
  67.       sys.stderr.write(message % self.pidfile)  
  68.       sys.exit(1)  
  69.       
  70.     #啟動監控  
  71.     self._daemonize()  
  72.     self._run()  
  73.   
  74.   def stop(self):  
  75.     #從pid文件中獲取pid  
  76.     try:  
  77.       pf = file(self.pidfile,'r')  
  78.       pid = int(pf.read().strip())  
  79.       pf.close()  
  80.     except IOError:  
  81.       pid = None  
  82.     
  83.     if not pid:   #重啟不報錯  
  84.       message = 'pidfile %s does not exist. Daemon not running!\n'  
  85.       sys.stderr.write(message % self.pidfile)  
  86.       return  
  87.   
  88.      #殺進程  
  89.     try:  
  90.       while 1:  
  91.         os.kill(pid, SIGTERM)  
  92.         time.sleep(0.1)  
  93.         #os.system('hadoop-daemon.sh stop datanode')  
  94.         #os.system('hadoop-daemon.sh stop tasktracker')  
  95.         #os.remove(self.pidfile)  
  96.     except OSError, err:  
  97.       err = str(err)  
  98.       if err.find('No such process') > 0:  
  99.         if os.path.exists(self.pidfile):  
  100.           os.remove(self.pidfile)  
  101.       else:  
  102.         print str(err)  
  103.         sys.exit(1)  
  104.   
  105.   def restart(self):  
  106.     self.stop()  
  107.     self.start()  
  108.   
  109.   def _run(self):  
  110.     """ run your fun"""  
  111.     while True:  
  112.       #fp=open('/tmp/result','a+')  
  113.       #fp.write('Hello World\n')  
  114.       sys.stdout.write('%s:hello world\n' % (time.ctime(),))  
  115.       sys.stdout.flush()   
  116.       time.sleep(2)  
  117.       
  118.   
  119. if __name__ == '__main__':  
  120.     daemon = Daemon('/tmp/watch_process.pid', stdout = '/tmp/watch_stdout.log')  
  121.     if len(sys.argv) == 2:  
  122.         if 'start' == sys.argv[1]:  
  123.             daemon.start()  
  124.         elif 'stop' == sys.argv[1]:  
  125.             daemon.stop()  
  126.         elif 'restart' == sys.argv[1]:  
  127.             daemon.restart()  
  128.         else:  
  129.             print 'unknown command'  
  130.             sys.exit(2)  
  131.         sys.exit(0)  
  132.     else:  
  133.         print 'usage: %s start|stop|restart' % sys.argv[0]  
  134.         sys.exit(2)  

運行結果:

       可以參考:http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/,它是當Daemon設計成一個模板,在其他文件中from daemon import Daemon,然后定義子類,重寫run()方法實現自己的功能。

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. class MyDaemon(Daemon):  
  2.     def run(self):  
  3.         while True:  
  4.             fp=open('/tmp/run.log','a+')  
  5.             fp.write('Hello World\n')  
  6.             time.sleep(1)  

        不足:信號處理signal.signal(signal.SIGTERM, cleanup_handler)暫時沒有安裝,注冊程序退出時的回調函數delpid()沒有被調用。
       然后,再寫個shell命令,加入開機啟動服務,每隔2秒檢測守護進程是否啟動,若沒有啟動則啟動,自動監控恢復程序。      

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #/bin/sh  
  2. while true  
  3. do  
  4.   count=`ps -ef | grep "daemonclass.py" | grep -v "grep"`  
  5.   if [ "$?" != "0" ]; then  
  6.      daemonclass.py start  
  7.   fi  
  8.   sleep 2  
  9. done  

三、python保證只能運行一個腳本實例

1、打開文件本身加鎖

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import fcntl, sys, time, os  
  4. pidfile = 0  
  5.   
  6. def ApplicationInstance():  
  7.     global pidfile  
  8.     pidfile = open(os.path.realpath(__file__), "r")  
  9.     try:  
  10.         fcntl.flock(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB) #創建一個排他鎖,並且所被鎖住其他進程不會阻塞  
  11.     except:  
  12.         print "another instance is running..."  
  13.         sys.exit(1)  
  14.   
  15. if __name__ == "__main__":  
  16.     ApplicationInstance()  
  17.     while True:  
  18.         print 'running...'  
  19.         time.sleep(1)  

       注意:open()參數不能使用w,否則會覆蓋本身文件;pidfile必須聲明為全局變量,否則局部變量生命周期結束,文件描述符會因引用計數為0被系統回收(若整個函數寫在主函數中,則不需要定義成global)。               

2、打開自定義文件並加鎖

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import fcntl, sys, time  
  4. pidfile = 0  
  5.   
  6. def ApplicationInstance():  
  7.     global pidfile  
  8.     pidfile = open("instance.pid", "w")  
  9.     try:  
  10.         fcntl.lockf(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB)  #創建一個排他鎖,並且所被鎖住其他進程不會阻塞  
  11.     except  IOError:  
  12.         print "another instance is running..."  
  13.         sys.exit(0)  
  14.   
  15. if __name__ == "__main__":  
  16.     ApplicationInstance()  
  17.     while True:  
  18.         print 'running...'  
  19.         time.sleep(1)  

3、檢測文件中PID

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import time, os, sys  
  4. import signal  
  5.   
  6. pidfile = '/tmp/process.pid'  
  7.   
  8. def sig_handler(sig, frame):  
  9.     if os.path.exists(pidfile):  
  10.         os.remove(pidfile)  
  11.     sys.exit(0)  
  12.   
  13. def ApplicationInstance():  
  14.     signal.signal(signal.SIGTERM, sig_handler)  
  15.     signal.signal(signal.SIGINT, sig_handler)  
  16.     signal.signal(signal.SIGQUIT, sig_handler)  
  17.   
  18.     try:  
  19.       pf = file(pidfile, 'r')  
  20.       pid = int(pf.read().strip())  
  21.       pf.close()  
  22.     except IOError:  
  23.       pid = None  
  24.     
  25.     if pid:  
  26.       sys.stdout.write('instance is running...\n')  
  27.       sys.exit(0)  
  28.   
  29.     file(pidfile, 'w+').write('%s\n' % os.getpid())  
  30.   
  31. if __name__ == "__main__":  
  32.     ApplicationInstance()  
  33.     while True:  
  34.         print 'running...'  
  35.         time.sleep(1)  

  

4、檢測特定文件夾或文件

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import time, commands, signal, sys  
  4.   
  5. def sig_handler(sig, frame):  
  6.     if os.path.exists("/tmp/test"):  
  7.         os.rmdir("/tmp/test")  
  8.     sys.exit(0)  
  9.   
  10. def ApplicationInstance():  
  11.     signal.signal(signal.SIGTERM, sig_handler)  
  12.     signal.signal(signal.SIGINT, sig_handler)  
  13.     signal.signal(signal.SIGQUIT, sig_handler)  
  14.     if commands.getstatusoutput("mkdir /tmp/test")[0]:  
  15.         print "instance is running..."  
  16.         sys.exit(0)  
  17.   
  18. if __name__ == "__main__":  
  19.     ApplicationInstance()  
  20.     while True:  
  21.         print 'running...'  
  22.         time.sleep(1)  

       也可以檢測某一個特定的文件,判斷文件是否存在:

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. import os  
  2. import os.path  
  3. import time  
  4.    
  5.    
  6. #class used to handle one application instance mechanism  
  7. class ApplicationInstance:  
  8.    
  9.     #specify the file used to save the application instance pid  
  10.     def __init__( self, pid_file ):  
  11.         self.pid_file = pid_file  
  12.         self.check()  
  13.         self.startApplication()  
  14.    
  15.     #check if the current application is already running  
  16.     def check( self ):  
  17.         #check if the pidfile exists  
  18.         if not os.path.isfile( self.pid_file ):  
  19.             return  
  20.         #read the pid from the file  
  21.         pid = 0  
  22.         try:  
  23.             file = open( self.pid_file, 'rt' )  
  24.             data = file.read()  
  25.             file.close()  
  26.             pid = int( data )  
  27.         except:  
  28.             pass  
  29.         #check if the process with specified by pid exists  
  30.         if 0 == pid:  
  31.             return  
  32.    
  33.         try:  
  34.             os.kill( pid, 0 )   #this will raise an exception if the pid is not valid  
  35.         except:  
  36.             return  
  37.    
  38.         #exit the application  
  39.         print "The application is already running..."  
  40.         exit(0) #exit raise an exception so don't put it in a try/except block  
  41.    
  42.     #called when the single instance starts to save it's pid  
  43.     def startApplication( self ):  
  44.         file = open( self.pid_file, 'wt' )  
  45.         file.write( str( os.getpid() ) )  
  46.         file.close()  
  47.    
  48.     #called when the single instance exit ( remove pid file )  
  49.     def exitApplication( self ):  
  50.         try:  
  51.             os.remove( self.pid_file )  
  52.         except:  
  53.             pass  
  54.    
  55.    
  56. if __name__ == '__main__':  
  57.     #create application instance  
  58.     appInstance = ApplicationInstance( '/tmp/myapp.pid' )  
  59.    
  60.     #do something here  
  61.     print "Start MyApp"  
  62.     time.sleep(5)   #sleep 5 seconds  
  63.     print "End MyApp"  
  64.    
  65.     #remove pid file  
  66.     appInstance.exitApplication()  

        上述os.kill( pid, 0 )用於檢測一個為pid的進程是否還活着,若該pid的進程已經停止則拋出異常,若正在運行則不發送kill信號。

 

5、socket監聽一個特定端口

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import socket, time, sys  
  4.   
  5.   
  6. def ApplicationInstance():  
  7.     try:      
  8.         global s  
  9.         s = socket.socket()  
  10.         host = socket.gethostname()  
  11.         s.bind((host, 60123))  
  12.     except:  
  13.         print "instance is running..."  
  14.         sys.exit(0)  
  15.   
  16. if __name__ == "__main__":  
  17.     ApplicationInstance()  
  18.     while True:  
  19.         print 'running...'  
  20.         time.sleep(1)  

可以將該函數使用裝飾器實現,便於重用(效果與上述相同):

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #!/usr/bin/env python  
  2. #coding: utf-8  
  3. import socket, time, sys  
  4. import functools  
  5.   
  6. #使用裝飾器實現  
  7. def ApplicationInstance(func):  
  8.     @functools.wraps(func)  
  9.     def fun(*args,**kwargs):  
  10.         import socket  
  11.         try:  
  12.             global s  
  13.             s = socket.socket()  
  14.             host = socket.gethostname()  
  15.             s.bind((host, 60123))  
  16.         except:  
  17.             print('already has an instance...')  
  18.             return None  
  19.         return func(*args,**kwargs)  
  20.     return fun  
  21.   
  22. @ApplicationInstance  
  23. def main():  
  24.     while True:  
  25.         print 'running...'  
  26.         time.sleep(1)  
  27.   
  28. if __name__ == "__main__":  
  29.     main()  

 

四、總結

(1)守護進程和單腳本運行在實際應用中比較重要,方法也比較多,可選擇合適的來進行修改,可以將它們做成一個單獨的類或模板,然后子類化實現自定義。
(2)daemon監控進程自動恢復避免了nohup和&的使用,並配合shell腳本可以省去很多不定時啟動掛掉服務器的麻煩。
(3)若有更好的設計和想法,可隨時留言,在此先感謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM