
python:通过发信号杀死父进程,子进程仍在运行的处理方法
当通过发信号杀死父进程时,子进程可能仍然会继续运行。以下是一些可能的解决方案:
方法 1:使用进程组 id
方法 2:在主进程启动后注册信号处理函数
立即进入“豆包AI人工智官网入口”;
立即学习“豆包AI人工智能在线问答入口”;
修改后的代码示例(文件 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)以上就是Python子进程在父进程被杀死后仍运行怎么办?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号