python子进程如何守护父进程防止意外退出?
网友回复
什么是守护进程?
守护进程是一种进程驻留内存的后台进程,它脱离终端控制,不受终端信号影响,即 Ctrl+C,通常守护进程用于周期性的执行某种任务或持续等待处理某些发生的事件。 python实现原理程序调用 fork()函数后,内存中的程序会在克隆出一份,然后使父进程退出,只保留子进程。父进程就是手终端信号控制的,例如Ctrl+C
如果你不想使用 root 用户运行,还可以通过 setuid,setgid 改变子进程的运行用户和组。
也可以改变子进程的工作目录和文件创建掩码
与守护进程通信需要用到信号处理。
示例代码
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
#================================================================================
# 这是一个演示日志切割的python程序
#================================================================================
import time,os,signal,sys,atexit
# from atexit import register
pidfile = "/tmp/netkiller.pid"
logdir = "/tmp"
logfile = logdir+"/netkiller.log"
logger = None
loop = True
job = True
# 保存进程ID
def savepid(pid):
with open(pidfile, 'w') as f:
f.write(str(os.getpid()))
# 注册退出函数,进程退出时自动移除pidfile文件
atexit.register(os.remove, pidfile)
# 从pidfile中读取进程ID
def getpid():
pid = 0
try:
with open(pidfile, 'r') as f:
pid = int(f.readline())
except FileNotFoundError as identifier:
print(identifier)
# print(pid)
return pid
# 创建日志
def createlog():
global logger
logger = open(logfile,mode="a+")
return logfile
# 写入日志
def log(level,msg):
l...点击查看剩余70%


