After a while of trying by myself I could not find any solution, and the internet resources do not seem to help.

I am trying to stop a python3 script called by command line in Linux using the CTRL+C keystroke, sadly it does not seem to work.

The program should stop after I call the libpcap function:

myInt = libpcap.next_ex(pcap_t_my, ctypes.byref(pcap_pkthdr), ctypes.byref(pcap_pkt_data))

This function receives an structure which contains a parameter/variable called time out. Which I am setting to 24000 ms in order to experiment with the libpcap functions.

Well it seems that while the program runs the libpcap.next_ex function interrupting this function is impossible with the signal library from python3 in order to stop the program. Nonetheless it reads the signal and performs the call to the handler after the timeout value has been exceeded.

Some of my code:

#Signal Handler fro CTRL+C
def shutDown_Handler(signal,frame):
    print("Program aborting by system handles KeyboardInterrupt...")
    SetDownProgram()
    print("Program aborted by system handles KeyboardInterrupt")
    sys.exit(0)


if __name__==  "__main__":
    ...
    signal.signal(signal.SIGINT, shutDown_Handler)
    try:
        ...
        
    except KeyboardInterrupt:
        print("Program aborting...")
        SetDownProgram()
        print("Program aborted")
    
    else:
        print("Program finished as planned")
    

The question would be.. How can I make that the program finishes immediately after I press the keystroke CTRL+C in the console where the python3 script is running?

Just mention that I am running the python3 script using a python environment. As: /home/$USER/Documents/myPyEnv/bin/python3

Does it affects the way you call SIGINT interrupt? Just mention that the program reads it, but it does not affect its behavior until the timeout set is over.

1

There are 1 best solutions below

0
Man789 On

Okay... I solved it using threads in Python. For anyone who reads the question I did as below and it seems to work:

  1. I imported "threading" library:
    import threading
  1. I create a new thread containing function which calls the libpcap function libpcap.netx_ex() and started it as not daemon service.
    threading.Thread(target=NormalFunction, daemon=False).start()

Or:

    NormalFunctionThread = threading.Thread(target=NormalFunction, daemon=False)
    NormalFunctionThread.start()
  1. I modified my signal handler to do not show traceback when CTRL+c/SIGNINT is sent.
    #Signal Handler fro CTRL+C

    def shutDown_Handler(signal,frame):
        print("Program aborting by system handles KeyboardInterrupt...")
        SetDownProgram()
        print("Program aborted by system handles KeyboardInterrupt")
        #sys.exit("Program aborted.")
        #os._exit in order to do not show traceback
        os._exit(0)

And now it works as expected! :D

Any improvements or notes will be appreciated.