转自:Python中创建守护进程

python 创建守护进程

  • python 的os.setdid()提供了类似linux c api的 setsid
  • 也可以通过unix双fork创建守护进程。

    几个相关的函数

  1. os.umask(0) #重设文件创建掩码,子进程会从父进程继承所有权限,可以通过调用这个方法将文件创建掩码初始化成系统默认。
  2. os.setsid() #调用系统的setsid(),创建一个新的会话并创建组id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
#coding:utf8
import sys, os
def main():
    """ A demo daemon main routine, write a datestamp to
        /tmp/daemon-log every 10 seconds.
    """
    import time
    = open("/tmp/daemon-log""w")
    while 1:
        f.write('%s/n' % time.ctime(time.time()))
        f.flush()
        time.sleep(10)
if __name__ == "__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (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, print eventual PID before
            print "Daemon PID %d" % pid
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)
    # start the daemon main loop
    main()

  

代码引用自从:http://code.activestate.com/recipes/66012/download/1/
  1. main为写时间戳的永久循环
  2. 运行后程序fork一个进程,如果fork成功则程序自己退出
  3. 通过setsid() 创建了一个独立于当前会话的进程
  4. 再一次fork一个进程,如果fork成功则当前程序退出
  5. 这时候进程的父进程就变成了 init,成为了一个独立的deamon

转自:Python实例浅谈之五Python守护进程和脚本单例运行

一、简介

守护进程最重要的特性是后台运行;它必须与其运行前的环境隔离开来,这些环境包括未关闭的文件描述符、控制终端、会话和进程组、工作目录以及文件创建掩码等;它可以在系统启动时从启动脚本/etc/rc.d中启动,可以由inetd守护进程启动,也可以有作业规划进程crond启动,还可以由用户终端(通常是shell)执行。
       Python有时需要保证只运行一个脚本实例,以避免数据的冲突。

二、Python守护进程

1、函数实现

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import sys, os
  4. '''将当前进程fork为一个守护进程
  5. 注意:如果你的守护进程是由inetd启动的,不要这样做!inetd完成了
  6. 所有需要做的事情,包括重定向标准文件描述符,需要做的事情只有chdir()和umask()了
  7. '''
  8. def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
  9. #重定向标准文件描述符(默认情况下定向到/dev/null)
  10. try:
  11. pid = os.fork()
  12. #父进程(会话组头领进程)退出,这意味着一个非会话组头领进程永远不能重新获得控制终端。
  13. if pid > 0:
  14. sys.exit(0)   #父进程退出
  15. except OSError, e:
  16. sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
  17. sys.exit(1)
  18. #从母体环境脱离
  19. os.chdir("/")  #chdir确认进程不保持任何目录于使用状态,否则不能umount一个文件系统。也可以改变到对于守护程序运行重要的文件所在目录
  20. os.umask(0)    #调用umask(0)以便拥有对于写的任何东西的完全控制,因为有时不知道继承了什么样的umask。
  21. os.setsid()    #setsid调用成功后,进程成为新的会话组长和新的进程组长,并与原来的登录会话和进程组脱离。
  22. #执行第二次fork
  23. try:
  24. pid = os.fork()
  25. if pid > 0:
  26. sys.exit(0)   #第二个父进程退出
  27. except OSError, e:
  28. sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
  29. sys.exit(1)
  30. #进程已经是守护进程了,重定向标准文件描述符
  31. for f in sys.stdout, sys.stderr: f.flush()
  32. si = open(stdin, 'r')
  33. so = open(stdout, 'a+')
  34. se = open(stderr, 'a+', 0)
  35. os.dup2(si.fileno(), sys.stdin.fileno())    #dup2函数原子化关闭和复制文件描述符
  36. os.dup2(so.fileno(), sys.stdout.fileno())
  37. os.dup2(se.fileno(), sys.stderr.fileno())
  38. #示例函数:每秒打印一个数字和时间戳
  39. def main():
  40. import time
  41. sys.stdout.write('Daemon started with pid %d\n' % os.getpid())
  42. sys.stdout.write('Daemon stdout output\n')
  43. sys.stderr.write('Daemon stderr output\n')
  44. c = 0
  45. while True:
  46. sys.stdout.write('%d: %s\n' %(c, time.ctime()))
  47. sys.stdout.flush()
  48. c = c+1
  49. time.sleep(1)
  50. if __name__ == "__main__":
  51. daemonize('/dev/null','/tmp/daemon_stdout.log','/tmp/daemon_error.log')
  52. main()

可以通过命令ps -ef | grep daemon.py查看后台运行的继承,在/tmp/daemon_error.log会记录错误运行日志,在/tmp/daemon_stdout.log会记录标准输出日志。

2、类实现

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. #python模拟linux的守护进程
  4. import sys, os, time, atexit, string
  5. from signal import SIGTERM
  6. class Daemon:
  7. def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
  8. #需要获取调试信息,改为stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr',以root身份运行。
  9. self.stdin = stdin
  10. self.stdout = stdout
  11. self.stderr = stderr
  12. self.pidfile = pidfile
  13. def _daemonize(self):
  14. try:
  15. pid = os.fork()    #第一次fork,生成子进程,脱离父进程
  16. if pid > 0:
  17. sys.exit(0)      #退出主进程
  18. except OSError, e:
  19. sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
  20. sys.exit(1)
  21. os.chdir("/")      #修改工作目录
  22. os.setsid()        #设置新的会话连接
  23. os.umask(0)        #重新设置文件创建权限
  24. try:
  25. pid = os.fork() #第二次fork,禁止进程打开终端
  26. if pid > 0:
  27. sys.exit(0)
  28. except OSError, e:
  29. sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
  30. sys.exit(1)
  31. #重定向文件描述符
  32. sys.stdout.flush()
  33. sys.stderr.flush()
  34. si = file(self.stdin, 'r')
  35. so = file(self.stdout, 'a+')
  36. se = file(self.stderr, 'a+', 0)
  37. os.dup2(si.fileno(), sys.stdin.fileno())
  38. os.dup2(so.fileno(), sys.stdout.fileno())
  39. os.dup2(se.fileno(), sys.stderr.fileno())
  40. #注册退出函数,根据文件pid判断是否存在进程
  41. atexit.register(self.delpid)
  42. pid = str(os.getpid())
  43. file(self.pidfile,'w+').write('%s\n' % pid)
  44. def delpid(self):
  45. os.remove(self.pidfile)
  46. def start(self):
  47. #检查pid文件是否存在以探测是否存在进程
  48. try:
  49. pf = file(self.pidfile,'r')
  50. pid = int(pf.read().strip())
  51. pf.close()
  52. except IOError:
  53. pid = None
  54. if pid:
  55. message = 'pidfile %s already exist. Daemon already running!\n'
  56. sys.stderr.write(message % self.pidfile)
  57. sys.exit(1)
  58. #启动监控
  59. self._daemonize()
  60. self._run()
  61. def stop(self):
  62. #从pid文件中获取pid
  63. try:
  64. pf = file(self.pidfile,'r')
  65. pid = int(pf.read().strip())
  66. pf.close()
  67. except IOError:
  68. pid = None
  69. if not pid:   #重启不报错
  70. message = 'pidfile %s does not exist. Daemon not running!\n'
  71. sys.stderr.write(message % self.pidfile)
  72. return
  73. #杀进程
  74. try:
  75. while 1:
  76. os.kill(pid, SIGTERM)
  77. time.sleep(0.1)
  78. #os.system('hadoop-daemon.sh stop datanode')
  79. #os.system('hadoop-daemon.sh stop tasktracker')
  80. #os.remove(self.pidfile)
  81. except OSError, err:
  82. err = str(err)
  83. if err.find('No such process') > 0:
  84. if os.path.exists(self.pidfile):
  85. os.remove(self.pidfile)
  86. else:
  87. print str(err)
  88. sys.exit(1)
  89. def restart(self):
  90. self.stop()
  91. self.start()
  92. def _run(self):
  93. """ run your fun"""
  94. while True:
  95. #fp=open('/tmp/result','a+')
  96. #fp.write('Hello World\n')
  97. sys.stdout.write('%s:hello world\n' % (time.ctime(),))
  98. sys.stdout.flush()
  99. time.sleep(2)
  100. if __name__ == '__main__':
  101. daemon = Daemon('/tmp/watch_process.pid', stdout = '/tmp/watch_stdout.log')
  102. if len(sys.argv) == 2:
  103. if 'start' == sys.argv[1]:
  104. daemon.start()
  105. elif 'stop' == sys.argv[1]:
  106. daemon.stop()
  107. elif 'restart' == sys.argv[1]:
  108. daemon.restart()
  109. else:
  110. print 'unknown command'
  111. sys.exit(2)
  112. sys.exit(0)
  113. else:
  114. print 'usage: %s start|stop|restart' % sys.argv[0]
  115. 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 plaincopy
  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 plaincopy
  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 plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import fcntl, sys, time, os
  4. pidfile = 0
  5. def ApplicationInstance():
  6. global pidfile
  7. pidfile = open(os.path.realpath(__file__), "r")
  8. try:
  9. fcntl.flock(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB) #创建一个排他锁,并且所被锁住其他进程不会阻塞
  10. except:
  11. print "another instance is running..."
  12. sys.exit(1)
  13. if __name__ == "__main__":
  14. ApplicationInstance()
  15. while True:
  16. print 'running...'
  17. time.sleep(1)

注意:open()参数不能使用w,否则会覆盖本身文件;pidfile必须声明为全局变量,否则局部变量生命周期结束,文件描述符会因引用计数为0被系统回收(若整个函数写在主函数中,则不需要定义成global)。               

2、打开自定义文件并加锁

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import fcntl, sys, time
  4. pidfile = 0
  5. def ApplicationInstance():
  6. global pidfile
  7. pidfile = open("instance.pid", "w")
  8. try:
  9. fcntl.lockf(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB)  #创建一个排他锁,并且所被锁住其他进程不会阻塞
  10. except  IOError:
  11. print "another instance is running..."
  12. sys.exit(0)
  13. if __name__ == "__main__":
  14. ApplicationInstance()
  15. while True:
  16. print 'running...'
  17. time.sleep(1)

3、检测文件中PID

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import time, os, sys
  4. import signal
  5. pidfile = '/tmp/process.pid'
  6. def sig_handler(sig, frame):
  7. if os.path.exists(pidfile):
  8. os.remove(pidfile)
  9. sys.exit(0)
  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. try:
  15. pf = file(pidfile, 'r')
  16. pid = int(pf.read().strip())
  17. pf.close()
  18. except IOError:
  19. pid = None
  20. if pid:
  21. sys.stdout.write('instance is running...\n')
  22. sys.exit(0)
  23. file(pidfile, 'w+').write('%s\n' % os.getpid())
  24. if __name__ == "__main__":
  25. ApplicationInstance()
  26. while True:
  27. print 'running...'
  28. time.sleep(1)

  

4、检测特定文件夹或文件

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import time, commands, signal, sys
  4. def sig_handler(sig, frame):
  5. if os.path.exists("/tmp/test"):
  6. os.rmdir("/tmp/test")
  7. sys.exit(0)
  8. def ApplicationInstance():
  9. signal.signal(signal.SIGTERM, sig_handler)
  10. signal.signal(signal.SIGINT, sig_handler)
  11. signal.signal(signal.SIGQUIT, sig_handler)
  12. if commands.getstatusoutput("mkdir /tmp/test")[0]:
  13. print "instance is running..."
  14. sys.exit(0)
  15. if __name__ == "__main__":
  16. ApplicationInstance()
  17. while True:
  18. print 'running...'
  19. time.sleep(1)

也可以检测某一个特定的文件,判断文件是否存在:

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

上述os.kill( pid, 0 )用于检测一个为pid的进程是否还活着,若该 pid的进程已经停止则抛出异常,若正在 运行则不发送kill信号。

5、socket监听一个特定端口

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import socket, time, sys
  4. def ApplicationInstance():
  5. try:
  6. global s
  7. s = socket.socket()
  8. host = socket.gethostname()
  9. s.bind((host, 60123))
  10. except:
  11. print "instance is running..."
  12. sys.exit(0)
  13. if __name__ == "__main__":
  14. ApplicationInstance()
  15. while True:
  16. print 'running...'
  17. time.sleep(1)

可以将该函数使用装饰器实现,便于重用(效果与上述相同):

[html] view plaincopy
  1. #!/usr/bin/env python
  2. #coding: utf-8
  3. import socket, time, sys
  4. import functools
  5. #使用装饰器实现
  6. def ApplicationInstance(func):
  7. @functools.wraps(func)
  8. def fun(*args,**kwargs):
  9. import socket
  10. try:
  11. global s
  12. s = socket.socket()
  13. host = socket.gethostname()
  14. s.bind((host, 60123))
  15. except:
  16. print('already has an instance...')
  17. return None
  18. return func(*args,**kwargs)
  19. return fun
  20. @ApplicationInstance
  21. def main():
  22. while True:
  23. print 'running...'
  24. time.sleep(1)
  25. if __name__ == "__main__":
  26. main()

四、总结

(1)守护进程和单脚本运行在实际应用中比较重要,方法也比较多,可选择合适的来进行修改,可以将它们做成一个单独的类或模板,然后子类化实现自定义。
(2)daemon监控进程自动恢复避免了nohup和&的使用,并配合shell脚本可以省去很多不定时启动挂掉服务器的麻烦。
(3)若有更好的设计和想法,可随时留言,在此先感谢!

Python中创建守护进程相关推荐

  1. 守护进程与后台进程(Python 创建守护进程)

    文章目录 一.守护进程与后台进程 1. 守护进程 1.1 代码实现 为什么要fork两次 umask权限掩码 进程组 会话组 2. 后台进程 3. 守护进程与后台进程区别 4. 使用场景总结 二.参考 ...

  2. python 守护程序检测进程是否存在_python创建守护进程的疑问

    我自己写了一个简易的下载和文件执行的客户端,如下 """ 省略若干代码 """ #执行下载函数 def do_script(): " ...

  3. ASP.NET Core Linux下为 dotnet 创建守护进程(必备知识)

    前言 在上篇文章中<ASP.NET Core Docker部署>中介绍了如何在 Docker 容器中部署我们的 asp.net core 应用程序,本篇主要是怎么样为我们在 Linux 或 ...

  4. python守护进程_让Python脚本成为守护进程

    Python部落(python.freelycode.com)组织翻译,禁止转载,欢迎转发. Python daemonizer 类 这是一个Python类,会使你的Python脚本成为守护进程,以使 ...

  5. python学习笔记——守护进程

    1 基本描述 守护进程:是系统中独立的后台服务进程, 特点:独立与终端并且周期性地执行某个任务,其生命周期长,一般随系统启动和终止. 缺点:进程的创建和销毁的时候需要消耗较多的计算机资源. 2 参考 ...

  6. Python多线程之守护进程

    Python多线程之守护进程 让主进程不在等待子进程,只要主进程结束,不管子进程是否执行完成,子进程都要随着主进程结束而中止 # coding:utf-8 # 作者 : 王 # 职业 : 嘉心糖 # ...

  7. Supervisor 为服务创建守护进程

    今天需要再服务上部署一个.net 方面的项目:当时开启服务的命令只能在前台执行:使用nohub CMD &等放在后台开启服务都会宕机:所以搜寻了Supervisor 这个解决办法,为服务创建守 ...

  8. 黑马程序员Linux系统开发视频之创建守护进程模型

    黑马程序员Linux系统开发视频之创建守护进程模型 1.创建子进程,父进程退出   所有工作在子进程中进行形式上脱离了控制终端 2.在子进程中创建新会话   setsid()函数   使子进程完全独立 ...

  9. Python中的自定义进程和进程池

    Python中的自定义进程和进程池 文章目录 Python中的自定义进程和进程池 一.自定义进程 1.步骤: 2.例 进程池 1.概念 2.介绍--multiprocess.Pool 3.非阻塞式进程 ...

  10. ora03135连接失去联系 进程id 0_进程组、会话、控制终端概念,如何创建守护进程?...

    守护进程 概念: 守护进程,也就是通常所说的Daemon进程,是Linux中的后台服务进程.周期性的执行某种任务或等待处理某些发生的事件. Linux系统有很多守护进程,大多数服务都是用守护进程实现的 ...

最新文章

  1. 浅析机器视觉在安防行业的应用
  2. Destroying the bus stations
  3. Oracle简单建立表空间
  4. 微型计算机通信与接口技术 pdf,微机原理与接口技术 pdf
  5. 洛谷回文数c语言,【普及-】洛谷P1015:回文数 一种解法
  6. CG-光栅图形学区域填充算法-学习笔记
  7. 部署java项目到阿里云服务器(centos7版本)
  8. php过滤除了文字数据英文,正则:过滤除英文和汉字的其它特殊符号
  9. GoBatch简介 —— 一款基于go语言的企业级批处理框架(Golang下的SpringBatch)
  10. 74HC138 芯片(38译码器)和74HC245 芯片(处理段码)
  11. 用Java编写程序实现找出100以内的质数
  12. ROS中launch文件和参数设置
  13. python爬取双色球历史数据_爬取双色球历史数据
  14. numpy 是否为零_玩数据必备 Python 库:Numpy 使用详解
  15. xp iis连接数破解
  16. u盘,tf卡,MP3,500次就报废了!
  17. 硬件工程师(电源设计)
  18. centos内核是linux吗,CentOS各版本的内核版本分别是什么?
  19. mysql 当前日期加3天_MySQL应用总结(十三)—函数的操作(3):日期时间函数
  20. C语言程序实例100个

热门文章

  1. 数据库专家:MySQL分片水很深
  2. 统计Linux服务器连接数
  3. 手动搭建最基础的 Retrofit + OkHttp + RxJava
  4. 【C语言】求1000-2000年的闰年,并统计个数
  5. 动态规划--凑硬币问题
  6. [转帖]onInterceptTouchEvent和onTouchEvent调用时序
  7. 一篇关于用户需求,己方产品(服务)与竞争对手的小清单
  8. iOS ASI--POST请求
  9. 2月份13个jQuery最佳插件推荐
  10. 用例规约要细致到万无一失吗?