What is the most efficient way (in terms of polling overhead) to request a Python program to stop (in a controlled way) from a Bash script. On python side I want a function (which executes as fast as possible) which returns true when a stop is requested or false if not. If true we save our work, release resources and exit.
For some simple tools I implemented the following:
The UNIX signal mechanism would be an excellent choice. You don't need any temporary files, and the polling overhead is essentially zero.
You may shutdown the following python program gracefully like so:
kill -USR1 $pid.
import signal import time import sys please_stop = False def setup_signal(): def handler(x,y): global please_stop please_stop = True signal.signal(signal.SIGUSR1, handler) def main_task(): for i in range(10): print "Working hard on iteration #%d"%i time.sleep(1) if please_stop: print "Stopping now" sys.exit(0) setup_signal() main_task()