0

I have a script which runs 2 threads infinitely. (Each thread is an infinite while loop) Whenever I run it normally, I use ctrl + Z or ctrl + C to stop its execution (depending on the OS). But ever since I added it to the /etc/rc.local file in Linux, for automatic startup upon boot, I am unable to use these commands to forcefully exit.

This has forced me to include something in the python script itself to cleanly exit when I type a certain key. How do I do so?

The problem is that I'm running a multithreaded application, which runs continuously and does not wait for any user inputs.

I added this to the start of a loop in my thread-

ip = raw_input()
if ip == 'quit':
    quit()

But this will NOT work since it blocks for a user input, and stops the script. I don't want the script to be affected at all by this. I just want it to respond when I want to stop it. My question is not what command to use (which is explained here- Python exit commands - why so many and when should each be used?), but how I should use it without affecting the flow of my program.

Community
  • 1
  • 1
sbhatla
  • 1,040
  • 2
  • 22
  • 34
  • 1
    How does your code handling the `KeyboardInterrupt` look like? Are you doing any clean up upon handling that exception? If not, sending the process a SIGTERM should be enough to stop it. – BlackJack Jul 15 '14 at 16:10
  • I just need to close 2 connections - one from each thread. `ser.close() sql_fn.close()` – sbhatla Jul 15 '14 at 17:21

2 Answers2

1

One way is to have the threads examine a global variable as a part of their loop, and terminate (break out of the loop and terminate, that is) when the variable is set.

The main thread can then simply set the variable and join() all existing threads before terminating. You should be aware that if the individual threads are blocked waiting for some event to occur before they next check whether the global variable has been set, then they will hang anyway until that event occurs.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
1

Keep the code that handles the KeyboardInterrupt and send it an INT signal to stop the program: kill -INT $pid from the shell, where $pid is the process ID (PID) of the program. That's essentially the same as pressing CTRL+C in a shell where the program runs in the foreground.

Writing the program's PID into a file right after it started, either from within the program itself or from the code which started it asynchronously, makes it easier to send a signal later, without the need to search for the process in the process list.

BlackJack
  • 4,476
  • 1
  • 20
  • 25