ros2.Crystal when Using rclcpp::executors::MultiThreadedExecutor::spin, if I use ctrl+c it will not shutdown the script
I used the following link to create the MultiThreadedExecutor code I have written bellow.
The issue I am having is that when using ctrl + c, I receive a
[INFO] [rclcpp]: signal_handler(signal_value=2)
message but, the thread still hangs. I do not quite understand how the ROS2 signal handler works. Is there a way I can catch the [INFO] [rclcpp]: signal_handler(signal_value=2) message to exit out of the spin and close the program?
using rclcpp::executors::MultiThreadedExecutor;
using builtin_interfaces::msg::Time;
std::shared_ptr<rclcpp::Node> master_node;
int value=0;
class test{
public:
static void topic_callback(test_msgs::msg::Test::SharedPtr msg)
{
std::cout <<" Subscriber Received [" << msg->data << "]" << std::endl;
value = msg->data;
}
};
int main()
{
rclcpp::shutdown();
test *t;
t = new test();
rclcpp::init(0, nullptr);
MultiThreadedExecutor executor;
master_node = rclcpp::Node::make_shared("MasterNode");
executor.add_node(master_node);
rclcpp::Publisher<test_msgs::msg::Test2>::SharedPtr publisher_;
rclcpp::Subscription<test_msgs::msg::Test>::SharedPtr subscription_;
subscription_ = master_node->create_subscription<test_msgs::msg::Test>("Test",t->topic_callback);
publisher_ = master_node->create_publisher<test_msgs::msg::Test2>("Test2");
rclcpp::Clock ros_clock(RCL_ROS_TIME);
Time ros_now = ros_clock.now();
std::thread executor_thread(std::bind(&MultiThreadedExecutor::spin, &executor));
executor_thread.detach();
while(rclcpp::is_initialized)
{
auto message = test_msgs::msg::Test();
message.header.stamp.nanosec = ros_now.nanosec;
publisher_->publish(message);
usleep(3000000);
}
rclcpp::shutdown();
}
Btw, why do you start with
rclcpp::shutdown()
?Why are you detaching the thread? Why not join it at the end of the main loop.
spin()
will exit whenSIGINT
is received automatically.The main thread has to be independent to the child thread that is used for the subscriber callback. The main thread is used to make heavy calculations and is constantly jumping to other classes. If i use join, the main thread gets stuck in the callback.
The reason I start with rclcpp::shutdown() is because the node took a while before shutting down. Sometimes when using ros2 node list, I would have multiple instances of the same node. I researched this issue and in one of the discussions it was mentioned to better have a shutdown in the beginning.
I will try to find the discussion and link to it.
If you are literally using
while(rclcpp:ok)
you are missing the parenthesis again to actually call the function (same as in the original snippet withwhile(rclcpp::is_initialized)
).I understand now. I have tried using while(rclcpp::ok()) and the example program shuts down. The segmentation fault I am experiencing in my main program is being caused by something else. The rclcpp shutdown is being properly called. Thank you for the patients you have showed.