Stop ros::spin()

asked 2020-07-21 04:06:24 -0500

Pombor gravatar image

updated 2022-01-22 16:10:40 -0500

Evgeny gravatar image


I would like to create a subscriber and publisher program that send messages and wait for an answer. The idea is to publish then listen the node. When an answer is received, it will stop listen the node and continue to execute the program.

Actually, I successfully write the subscriber and publisher, but i'm not able to handle the ros::spin. I don't know how to stop it or pause it, despite looking some forums.

Here's my run function :


Here's my callback function :

void callback_listener(const std_msgs::String::ConstPtr& msg)
   if (msg == "ok") // something like this
      //here I should stop the ros::spin()

Help would be appreciated.


edit retag flag offensive close merge delete


Try to use ros::spinOnce in your code

kosmastsk gravatar image kosmastsk  ( 2020-07-22 01:33:14 -0500 )edit

Already used it, but not working.

Pombor gravatar image Pombor  ( 2020-07-22 01:44:08 -0500 )edit

To support @kosmastsk comment you need to know that ros::spin directive is a blocking function, hence it will block all your execution at the main process. You may use ros::spinOnce that already implement a type of wait/synchronization for processing messages.

If that does not fit your set up, just change the main process of your program with a

bool process = true;

void callback_listener(const std_msgs::String::ConstPtr& msg)
   if (msg == "ok")
     process = false;

int main(int argc, char** argv)
   //Do your process here.
return 0;
Weasfas gravatar image Weasfas  ( 2020-07-22 05:04:11 -0500 )edit

That's not really what I'm looking for. I don't use any "while" because it's a GUI with Qt5. ros::AsyncSpinner spinner(0) seems doing the behavior that i'm looking for. But when I write it in main, I get some errors about threads. So, i'm a little bit lost.

Pombor gravatar image Pombor  ( 2020-07-27 08:23:29 -0500 )edit

If you are dealing with a Qt5 project you do not need to write that in the main process where you instantiate the main Qt Window, you should have a Node running in another thread providing ROS communications with the Qt application, In that case you will have a "while" ros::ok() running in his own thread node, while the Qt5 application will be running in the main process. Nevertheless either you use a custom callback queue to decide when to dequeue the message and resume execution or perform a wait in the Qt thread to only resume the execution when start is called or the wait finishes, I am still do not know why you want to block ROS execution but there is another probable approach that you can use and that is waitForMessage which will wait until a message is received and drops connection.

Weasfas gravatar image Weasfas  ( 2020-07-28 06:03:52 -0500 )edit