I have the following standard implementation of capturing Ctrl+C:
def signal_handler(signal, frame):
status = server.stop()
print("[{source}] Server Status: {status}".format(source=__name__.upper(),
status=status))
print("Exiting ...")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
On server.start()
I am starting a threaded instance of CherryPy. I created the thread thinking that maybe since CherryPy is running, the main thread is not seeing the Ctrl+C. This did not seem to have any affect but posting the code as I have it now:
__main__:
server.start()
server:
def start(self):
# self.engine references cherrypy.engine
self.__cherry_thread = threading.Thread(target=self.engine.start)
self.status['running'] = True
self.status['start_time'] = get_timestamp()
self.__cherry_thread.start()
def stop(self):
self.status['running'] = False
self.status['stop_time'] = get_timestamp()
self.engine.exit()
self.__thread_event.set()
return self.status
When I press Ctrl+C the application does not stop. I have placed a breakpoint in the signal_handler
above and it is never hit.
It's not quite clear what you want to achieve in the end, but it looks like you miss important point of CherryPy design.
CherryPy state and component orchestration is built around the message bus. To you as a developer it's also an abstraction from OS-specific signalling. So if you want to have a thread, it is a good idea to wrap in into CherryPy plugin which will adhere to state of the server.
UPDATE
More explicitly about handling SIGINT signal. Here's the FSM diagram from the first link.
Your interest is either
STOPPING
orEXITING
as both relate to handling SIGINT. The difference is thatSTOPPING
may occur several times e.g. when the server is daemonised SIGHUP makes it restart. So you can just put your termination routine inExamplePlugin.exit
.