How does the compiler read rospy.on_shutdown(shutdownhook) when the compiler is on a different line

From the previous posts I understand that upon pressing Ctrl+c , the function written within the parenthesis of rospy.on_shutdown is called.

My question is, in the programs I have seen, rospy.on_shutdown(func) is often only called once usually at the beginning of the program. Yet when the compiler reads it once ,the function within paranthesis gets activated on shutdown no matter where in the program we are.

It is my understanding that a function only works when the compiler reaches that function’s call line. The compiler compiles from top to bottom, how can the rospy.on_shutdown(func) be called when that is not the line on which the compiler is present?


As far as I understand it, you are defining here a callback, which is a function called asyncronously. That means that it will be called no matter where the main thread of the program is.

@duckfrost2 , asyncronous functions is a new concept to me and it was not covered in the python tutorial. But now that i have its name, i can takeup tutorials to learn more on it.

Thanks @duckfrost2 for the quick reply

Suggestion to Construct : asyncronous func to be covered in Construct’s python tutorial since almost every program uses rospy.on_shutdown()

Actually the line


does not call the function. It only specifies or registers the function to be called whenever ROS is shutting down.

So, whenever ROS gets a shutdown signal, it checks the “on shutdown” register and calls the function specified (if any).

Yes, a function can be called when the compiler reaches a line the calls the function, but it can also be called by an external “hook” (such as the rospy.on_shutdown and subscriber callback hooks).

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.