a文件
import multiprocessing
import os
import signal
import time
def process1():
while True:
print("子进程运行中")
time.sleep(1)
# 定义信号处理函数
def handle_signal(signum, frame):
print(signum)
if signum == signal.SIGTERM:
print("Received SIGTERM signal. Deleting PID file...")
try:
os.remove("/var/run/crawler.pid")
print("PID file deleted successfully.")
except Exception as e:
print("Error deleting PID file:", e)
# 注册信号处理函数
signal.signal(signal.SIGTERM, handle_signal)
if "__main__" == __name__:
a = multiprocessing.Process(target=process1)
a.daemon = True
a.start()
child_pid = a.pid
parent_pid = os.getpid()
with open("/var/run/crawler.pid", 'w') as f:
f.write(str(parent_pid))
a.join()
print("父进程pid:", parent_pid)
print("子进程pid", child_pid)
# os.waitpid(child_pid, 0)
b文件
import os
import signal
with open('/var/run/crawler.pid', 'r') as f:
try:
pid = int(f.read())
os.kill(pid, signal.SIGTERM)
print("Signal sent successfully to process", pid)
except Exception as e:
print("Error sending signal:", e)
这里说明一下,据wiki了解到的资料信息,进程组是主进程和子进程组成的一个集合。
进程组的作用就是用来控制信号的分配到它的所有成员。所以你要杀掉主进程和相应的子进程,就要用
os.killpg
去向这个进程组去发送kill信号,否则常规的os.kill
只能杀死单进程,而无法将信号量传递到子进程中,还需要你单独手动清除子进程。同样对另外一个文件修改: