Why does ctrl + c not stop tornado server on windows ?
This code is not executed: print 'get sig:%d' % signum
import signal
import tornado
import tornado.web
import tornado.httpserver
class DefaultHandler(tornado.web.RequestHandler):
def get(self):
self.set_status(200, 'OK')
self.write('hello guest')
def post(self):
self.get()
class Receiver(object):
def __init__(self, address=None, port=8100, gzip=False):
if not address:
address = '0.0.0.0'
self.address = address
self.port = port
self.gzip = gzip
self.http_server = None
def start(self):
settings = dict(
)
application = tornado.web.Application([
(r"/", DefaultHandler),],
**settings)
self.http_server = tornado.httpserver.HTTPServer(application, decompress_request=self.gzip)
self.http_server.listen(self.port)
tornado.ioloop.IOLoop.instance().start()
def shutdown(self):
if self.http_server is not None:
self.http_server.stop()
tornado.ioloop.IOLoop.instance().stop()
if __name__ == '__main__':
receiver = Receiver(port=8901)
def sig_handler(signum, frame):
print 'get sig:%d' % signum
receiver.shutdown()
signal.signal(signal.SIGTERM, sig_handler)
signal.signal(signal.SIGINT, sig_handler)
receiver.start()
My solution:
only main thread can handle signal, so use thread to start receiver and let main thread do some fake work to keep alive
threading.Thread(target=receiver.start).start()
while 1:
try:
time.sleep(2)
except:
break