ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Automatic node shutdown if topic is no longer receiving messages

asked 2022-01-03 15:17:45 -0500

ashwath1993 gravatar image


I have a node that receives camera messages. I want the node to shutdown when the rosbag is done playing. I know I can do this with roslaunch. But I wanted to know if I could do this with code.

I noticed that my code works for some recordings and fails for others.

void callback(const sensor_msgs::ImageConstPtr& msg)
if(sub.getNumPublishers() == 0)
 // run main algo and write results
   // process message


Is there a way to shutdown the node outside the callback? My subscriber is part of a class and the subscriber is initialized with the constructor.

MyClass(ros::NodeHandle& n)
  sub = n.subscribe<sensor_msgs::Image>("/camera/image_color", 100, &MyClass::callback, this);

My node is defined as follows

int main(int argc, char * argv[])
ros::init(argc, argv, "calib_node");

ros::NodeHandle n;
MyClass obj(n);

return 0;
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-01-04 14:06:06 -0500

Mike Scheutzow gravatar image

In your main(), you can replace the ros::spin() with a while loop that does whatever you want it to. In this example, check_for_done() is a function that you provide. If you use this approach, be sure you sleep() on every iteration of the while loop.

ros::Duration d(0.100);
while(ros::ok) {
    if (check_for_done()) {
edit flag offensive delete link more


This was sufficient for what I wanted to achieve. Thanks!

ashwath1993 gravatar image ashwath1993  ( 2022-02-06 09:10:36 -0500 )edit

Question Tools



Asked: 2022-01-03 15:17:45 -0500

Seen: 279 times

Last updated: Jan 04 '22