3

In the code below I am creating a thread that opens up a function called candump. Candump monitors an input channel and returns values to std out as data comes in.

What I want to do is have control over when this terminates (ie, a fixed amount of time after cansend). After looking through the documentation it seems like join might be the right way to go?

I'm not sure. Any thoughts?

import threading
from subprocess import call, Popen,PIPE
import time

delay=1

class ThreadClass(threading.Thread):
  def run(self):
    start=time.time()
    proc=Popen(["candump","can0"],stdout=PIPE)
    while True:
        line=proc.stdout.readline()
        if line !='':
            print line

t = ThreadClass()
t.start()
time.sleep(.1)
call(["cansend", "can0", "-i", "0x601", "0x40", "0xF6", "0x60", "0x01", "0x00", "0x00", "0x00", "0x00"])
time.sleep(0.01)
#right here is where I want to kill the ThreadClass thread
Chris
  • 9,603
  • 15
  • 46
  • 67
  • 1
    There's an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here. Are you asking how to terminate a thread, or are you asking how to put a timeout on a subprocess and you just thought thread termination was the way to do it? If the former, this is a dup of [Is there any way to kill a Thread in Python?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python). If the latter, it's not. (You _can_ terminate a _process_, which makes this easy.) – abarnert Mar 05 '13 at 00:26

2 Answers2

1
import subprocess as sub
import threading

class RunCmd(threading.Thread):
    def __init__(self, cmd, timeout):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.timeout = timeout

    def run(self):
        self.p = sub.Popen(self.cmd)
        self.p.wait()

    def Run(self):
        self.start()
        self.join(self.timeout)

        if self.is_alive():
            self.p.terminate()
            self.join()

RunCmd(["./someProg", "arg1"], 60).Run()

cited from : Python: kill or terminate subprocess when timeout

Community
  • 1
  • 1
zzk
  • 1,347
  • 9
  • 15
0

It may not be the best way to terminate a thread, but this answer provides a way to kill a thread. Beware that you may also need to implement a way for threads to be unkillable in critical sections of their code.

Community
  • 1
  • 1
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117