
python:通过发信号杀死父进程,子进程仍在运行的处理方法
当通过发信号杀死父进程时,子进程可能仍然会继续运行。以下是一些可能的解决方案:
方法 1:使用进程组 id
- 获取父进程和子进程的进程组 id:使用 os.getpgid() 代替 os.getpid(),可以获取进程组 id。进程组是包含主进程及其所有子进程的集合。
- 发送信号到进程组:使用 os.killpg() 代替 os.kill(),可以将信号发送到整个进程组,从而同时终止父进程和所有子进程。
方法 2:在主进程启动后注册信号处理函数
立即学习“Python免费学习笔记(深入)”;
- 在创建子进程后注册信号处理程序:将信号处理函数的注册放在创建子进程的过程之后,以确保在子进程启动后仍然有效。
修改后的代码示例(文件 a.py):
# a.py
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:
if os.path.exists("crawler.pid"):
os.remove("crawler.pid")
print("pid file deleted successfully.")
except exception as e:
print("error deleting pid file:", e)
# 注册信号处理函数
if "__main__" == __name__:
a = multiprocessing.process(target=process1)
a.daemon = true
a.start()
child_pid = a.pid
parent_pid = os.getpid()
parent_pid_group = os.getpgid(parent_pid)
signal.signal(signal.sigterm, handle_signal)
with open("crawler.pid", "w") as f:
f.write(str(parent_pid_group))
a.join()
print("父进程pid:", parent_pid)
print("子进程pid", child_pid)
# os.waitpid(child_pid, 0)修改后的代码示例(文件 b.py):
# b.py
import os
import signal
with open("crawler.pid", "r") as f:
try:
pid = int(f.read())
os.killpg(pid, signal.SIGTERM)
print("Signal sent successfully to process", pid)
except Exception as e:
print("Error sending signal:", e)










