3

I'm making a Python script that sniffs the network traffic for specific packets. For that, I have several threads. (Let's assume that they are needed.)

I would like to stop these threads when CTRL+C is pressed.

import threading
from scapy.* import all

class myThread(threading.Thread):
    def __init__(self, protocol):
        threading.Thread.__init__(self)
        self.protocol = protocol
    def run(self):
        my_function(self.protocol)

def callback(packet):
    # Do stuff

def my_function(protocol):
    # Do stuff
    sniff(filter=protocol, prn=callback, store=0)

t1 = myThread("udp")
t2 = myThread("tcp")

t1.start()
t2.start()

# magic stuff so that CTRL+C stops the threads

t1.join()
t2.join()

print("Exiting")

How can I achieve that?

Jzoe
  • 31
  • 2
  • Possible duplicate: [http://stackoverflow.com/questions/323972/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) – Chiheb Nexus Jan 05 '17 at 21:15
  • This method works *if you can afford it*, it's not the case here, I don't see how I could stop the sniff function. – Jzoe Jan 05 '17 at 21:21
  • If you simply want to exit in response to the Ctrl-C anyway, then just trap the `KeyboardInterrupt` exception in the main thread and call `os._exit`. All threads will be destroyed along with the process. – Gil Hamilton Jan 06 '17 at 17:05

0 Answers0