简体   繁体   中英

how to kill a system process invoked in a thread

I invoke the top process in a thread.

How could I kill the thread and top process after other process are finished or after a certain of time ?

class ExternalProcess(threading.Thread):   
    def run(self):
        os.system("top")


def main():

    # run the thread and 'top' process here

    # join all other threads
    for thread in self.thread_list:
        thread.join()

    # stop the thread and 'top' process here

If you're on a Unix-like platform you can use ps -A for list your process so try this :

import subprocess, signal
import os
def killproc(procname):
 p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
 out, err = p.communicate()
 for line in out.splitlines():
   if procname in line:
    pid = int(line.split(None, 1)[0])
    os.kill(pid, signal.SIGKILL)

killproc('firefox') #this is an example 

if you aren't in unix use proper command instead ps -A

Use process group to handle the sub-process, so you can send a signal kill, to your sub-process.

import os import signal import subprocess

class ExternalProcess(threading.Thread):   
    def run(self):
        # The os.setsid() is passed in the argument preexec_fn so
        # it's run after the fork() and before  exec() to run the shell. 
        proc = subprocess.Popen("top", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) 

        os.killpg(proc.pid, signal.SIGTERM)  # Send the signal to all the process groups

def main():

    # run the thread and 'top' process here

    # join all other threads
    for thread in self.thread_list:
        thread.join()

    # stop the thread and 'top' process here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM