简体   繁体   中英

How to kill a python program (which includes ROS and twisted protocol) in a clean way when Ctrl+c is pressed?

I have made a ROS node that establishes connection with the client using twisted protocol of python. The program is working as expected but when I try to kill the program using Ctrl+c, it displays following error message:

[server_send_command_ver3-4] escalating to SIGTERM

I have included a portion of my code below:

if __name__ == '__main__':
   try:
    #node initialization
    rospy.init_node('listen', anonymous = True)

    #publisher to publish message to clientconnection to display connection status on GUI
    connect = rospy.Publisher("status", String, queue_size = 10)
    connect.publish(" Lost Connection")

    #twisted protocol and listen at port 80
    factory = Factory()
    factory.protocol = NewFactory
    factory.clients = []  
    reactor.listenTCP(80, factory)
    reactor.run()

  except rospy.ROSInterruptException:
    pass

A good way to do that would be using rospy.on_shutdown() .

Basically, when implemented, this function will be called once the node shutdown is requested (like a Ctrl + C press). In your case, you can close your connection inside this function and handle whatever you need before the complete shutdown (eventually sth like reactor.close() ).

Here's an example taken from here :

def myhook():
  print "shutdown time!"

rospy.on_shutdown(myhook)

The rospy already implements a handler for signals ( http://wiki.ros.org/rospy/Overview/Initialization%20and%20Shutdown ) and should handle the ctrl+c (SIGINT) just fine.

However you are running a twisted instance and the reactor.run() is a blocking call. The signal that you are sending is not closing the twisted thread. Since no reaction is being taken by the program, the rospy escalates the SIGINT to a SIGTERM to force the program to close.

To be able to close your program gracefully you can either implement a hook on rospy to close the twisted instance (not sure if that will work)

rospy.on_shutdown(reactor.stop)

or use the python signal library to implement a handler for the SIGINT that gracefully closes all the instances in your program ( https://docs.python.org/2/library/signal.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM