I’ve done a deep dive to see what is happening here, and it seems Humble and more recent distros are having issues precisely in that area. It seems like it’s not something you are coding incorrectly, but rather a racy condition that happens that prevents you from publishing any ROS 2 information when there is a keyboardinterrupt.
Here is an interesting open issue related to this:
opened 01:08PM - 22 May 24 UTC
help wanted
## Bug report
It looks like the callback that can be registered via `context.… on_shutdown` is never called.
**Required Info:**
- Operating System:
- Ubuntu 22.04
- Installation type:
- binary
- Version or commit hash:
- 4.1.5
- Client library (if applicable):
- rclpy
#### Steps to reproduce issue
Register a callback to on_shutdown and then try various methods of exiting the node
```
def shutdown_handler():
print("exit")
def main(args=None):
rclpy.init(args=args)
node = Node("TestNode")
node.context.on_shutdown(shutdown_handler)
rclpy.get_default_context().on_shutdown(shutdown_handler)
rclpy.spin(node)
```
I tried sending various signals: SIGINT, SIGTERM, SIGQUIT
#### Expected behavior
`exit` should be printed twice
#### Actual behavior
Prints nothing
#### Additional information
I also tried calling `try_shutdown`:
```
try:
rclpy.spin(node)
except (KeyboardInterrupt, rclpy.executors.ExternalShutdownException):
pass
finally:
rclpy.try_shutdown()
```
But this didn't result into `on_shutdown` being called either.
If one tries to explicitly shutdown the context:
```
finally:
node.context.shutdown()
```
The following error is thrown:
`failed to shutdown: rcl_shutdown already called on the given context`
### Related Issues
This issue is probably related to. But according to the issues I found `on_shutdown` should be at least called if the node is properly exited (or if try_shutdown is called?)
https://github.com/ros2/rclpy/issues/532
https://github.com/ros2/rclpy/issues/1077 <- This is actually what I am looking for as I do want to do some cleanup
I don’t know how to go around this issue. I think this issue is related so let’s see if @albertoezquerro has a workaround.
1 Like