猿问

子进程:在Windows中删除子进程

在Windows上,subprocess.Popen.terminate调用win32的TerminalProcess。但是,我看到的行为是我尝试终止的进程的子进程仍在运行。这是为什么?如何确保杀死该进程启动的所有子进程?

小怪兽爱吃肉
浏览 688回答 3
3回答

神不在的星期二

通过使用psutil:import psutil, osdef kill_proc_tree(pid, including_parent=True):        parent = psutil.Process(pid)    children = parent.children(recursive=True)    for child in children:        child.kill()    gone, still_alive = psutil.wait_procs(children, timeout=5)    if including_parent:        parent.kill()        parent.wait(5)me = os.getpid()kill_proc_tree(me)

慕丝7291255

这是Job对象方法的示例代码,但不是subprocess使用win32api.CreateProcessimport win32processimport win32jobstartup = win32process.STARTUPINFO()(hProcess, hThread, processId, threadId) = win32process.CreateProcess(None, command, None, None, True, win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup)hJob = win32job.CreateJobObject(None, '')extended_info = win32job.QueryInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation)extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSEwin32job.SetInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation, extended_info)win32job.AssignProcessToJobObject(hJob, hProcess)
随时随地看视频慕课网APP
我要回答