PHP前端开发

Python子进程在父进程被杀死后仍运行怎么办?

百变鹏仔 5天前 #Python
文章标签 进程

python:通过发信号杀死父进程,子进程仍在运行的处理方法

当通过发信号杀死父进程时,子进程可能仍然会继续运行。以下是一些可能的解决方案:

方法 1:使用进程组 id

方法 2:在主进程启动后注册信号处理函数

立即学习“Python免费学习笔记(深入)”;

修改后的代码示例(文件 a.py):

# a.pyimport multiprocessingimport osimport signalimport timedef 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.pyimport osimport signalwith 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)