0
$\begingroup$

I need a C++ script which can read through bags and do some processing, basically the structure is going to be

int main(int argc, char* argv[]){
  ros::init(argc, argv, node_name);
  ros::NodeHandle nh("~");

  // do stuff

  return 0;
}

where I create the nodehandle only to have a parameter server. I explicitly don't want this to have subscribers, as it'll be much faster just reading the bag and processing.

The problem is that this does not exit correctly, when ctrl+C the program keeps going and upon reaching return 0; it requires a ctrl+C for the launch file to close out on the terminal. How can I fix this? I'd like to avoid wrapping the entirety of // do stuff with a while (ros::ok())

Edit: The script responded fine to ctrl+C when it was rosrun, but launching it (which I need to for easy including yaml file, causes this behavior.

$\endgroup$
4
  • $\begingroup$ Welcome to Robotics Stack Exchange! Please update your question as it is difficult to understand your question. The tiny code you shared provides no information. I suggest sharing a minimum working example. Thank you for your kind cooperation. $\endgroup$
    – ravi
    Sep 7, 2023 at 3:29
  • $\begingroup$ There isn't a whole lot more to it, theres no spin or any normal ros content (lik pub/sub). It's just creating a node, accessing params, reading the bag file, and doing some processing. 100% offline $\endgroup$ Sep 7, 2023 at 4:14
  • $\begingroup$ And the problems are that ctrl+C doesn't interrupt the // do stuff section, nor does it end the launch file when the C++ script finishes. There's really not much more to it than that. What part is it you're not understanding? $\endgroup$ Sep 7, 2023 at 4:16
  • $\begingroup$ Try required="true" in the launch file wiki.ros.org/roslaunch/XML/node#Attributes $\endgroup$ Sep 7, 2023 at 15:50

1 Answer 1

0
$\begingroup$

It sounds like you'd like to avoid the while(ros::ok()) pattern because you're reading from a bag file, so rather than running in a loop you plan to step through each individual message and then exit when complete (or sooner, if ctrl-c is detected).

We can use ros::ok() outside of a while loop. Here's a modified version of the rosbag code API example that does that:

#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <std_msgs/Int32.h>

rosbag::Bag bag;
bag.open("test.bag");  // BagMode is Read by default

for(rosbag::MessageInstance const m: rosbag::View(bag))
{
  // read data
  std_msgs::Int32::ConstPtr i = m.instantiate<std_msgs::Int32>();
  if (i != nullptr)
    std::cout << i->data << std::endl;

  // exit loop if node is told to shut down
  if (!ros::ok())
    break;
}

bag.close();
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.