Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux中的Python:使用shell杀死进程和子进程_Python_Linux_Shell - Fatal编程技术网

Linux中的Python:使用shell杀死进程和子进程

Linux中的Python:使用shell杀死进程和子进程,python,linux,shell,Python,Linux,Shell,Q:给定一个一直在运行的python程序,该程序作为其子程序运行另一个python程序,如何使用python shell杀死进程[即,获取进程PID,然后执行kill-9] 更多详细信息: 我有一个脚本如下: from subprocess import * while True: try: Popen("python ...").wait() # some scrpipt except: exit(1) try: Pop

Q:给定一个一直在运行的python程序,该程序作为其子程序运行另一个python程序,如何使用python shell杀死进程[即,获取进程PID,然后执行
kill-9
]

更多详细信息:

我有一个脚本如下:

from subprocess import *

while True:
    try:
        Popen("python ...").wait() # some scrpipt
    except:
        exit(1)
    try:
        Popen("python ...").wait() # some scrpipt
    except:
       exit(1)
现在,当我想杀死这个进程及其子进程时,我:

  • 运行
    “ps-ef | grep python”
    获取PID
  • 运行
    kill-9
    终止进程
  • 结果:进程在分配了新的PID后继续运行

    是否有一种优雅的方式可以使进程在终止时优雅地退出

    是否有一种优雅的方式可以使进程在终止时优雅地退出

    当你
    杀死-9
    的时候没有。使用SIGINT(
    -2
    )或SIGTERM(
    -15
    )杀死,并通过注册处理优雅退出的清理功能,使用信号模块捕获该信号

    import sys
    import signal
    
    def cleanup_function(signal, frame):
        # clean up all resources
        sys.exit(0)
    
    signal.signal(signal.SIGINT, cleanup_function)
    

    在此代码中,父级将等待子级的退出状态。若父级正在获取其存在状态,则只有它将继续进行下一次迭代

    此外,您无法捕获
    SIGKILL
    SIGKILL
    SIGSTOP
    是无法捕获的信号)

    -9
    表示
    SIGKILL

    您可以在任何其他信号的情况下实现
    信号
    处理程序

    import os
    import time
    
    
    def my_job():
        print 'I am {0}, son/daughter of {1}'.format(os.getpid(), os.getppid())
        time.sleep(50)
        pass
    
    
    if __name__ == '__main__':
        while True:
            pid = os.fork()
            if pid > 0:
                expired_child = os.wait() # if child is getting killed, will return a tuple containing its pid and exit status indication
                if expired_child:
                    continue
            else:
                my_job()
    

    你想从哪里杀它?