Search code examples
pythonshutdownrossimplehttpserverrospy

Stop serve_forever when rospy.is_shutdown


I have the following Python program to start an HTTP server and a ROS node.

httpd = ThreadingHttpServer()

rospy.init_node('server')
rospy.on_shutdown(httpd.shutdown)

try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass

httpd.server_close()

I want the program to terminate

  • when I call httpd.shutdown() (e.g. after receiving a /kill command),
  • when ROS is shutting down (i.e. if rospy.is_shutdown()) and
  • when I press Ctrl+C (this is least important).

Somehow I'm struggling with recognizing the ROS shutdown, even though I tried rospy.on_shutdown() and alternatively an own while loop calling httpd.handle_request().

With the current version, the node (started with rosrun) does not stop when shutting down roscore.

How can I combine these two modules reasonably?


Solution

  • I believe you can stop by registering the socket close function on the (or your own function that calls it) as a rospy shutdown handler.

       def shutdown_hook():
           print "Trying to shut down server"
           httpd.shutdown()
    
       rospy.on_shutdown(shutdown_hook)
    

    If shutdown() doesn't work, try httpd.socket.close()