參考:1.https://answers.ros.org/question/27655/what-is-the-correct-way-to-do-stuff-before-a-node-is-shutdown/
2.http://wiki.ros.org/roscpp/Overview/Initialization%20and%20Shutdown
小車由于在關(guān)閉節(jié)點后無法發(fā)布Twist消息而不能停止冈爹,查找后發(fā)現(xiàn)可以使用自己的shutdown回調(diào)函數(shù)解決這一問題喘帚。思路是在ros::init中使用ros::init_options::NoSigintHandler選項逼蒙,然后用signal函數(shù)注冊自己的回調(diào)函數(shù)饺律,用該回調(diào)函數(shù)控制原子變量g_request_shutdown從而獲得節(jié)點的運行狀態(tài)誓军,最后用ros::shutdown()手動關(guān)閉節(jié)點听想。
在python中可以直接使用rospy.on_shutdown()來更改節(jié)點關(guān)閉時的行為琼掠。
#include <ros/ros.h>
#include "calc_motion.h"
#include "geometry_msgs/Twist.h"
#include <signal.h>
// Signal-safe flag for whether shutdown is requested
sig_atomic_t volatile g_request_shutdown = 0;
void mySigIntHandler(int sig){
g_request_shutdown = 1;
}
int main(int argc, char **argv){
// 關(guān)閉時使用自己的回調(diào)函數(shù)
ros::init(argc, argv, "motion", ros::init_options::NoSigintHandler);
signal(SIGINT, mySigIntHandler);
ros::NodeHandle nh;
geometry_msgs::Twist twist;
CalcMotion cm;
ros::Publisher pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 5);
ros::Subscriber sub = nh.subscribe<ball_follow::Direction>("/direction", 1, &CalcMotion::getDirection, &cm);
ros::Rate r(10);
while(!g_request_shutdown){
ros::spinOnce();
// ROS_DEBUG("Twist x = %f, z = %f", twist.linear.x, twist.angular.z);
cm.calcTwist(twist);
pub.publish(twist);
r.sleep();
}
twist.linear.x = twist.angular.z = 0;
pub.publish(twist);
// 手動關(guān)閉ros節(jié)點
ros::shutdown();
return 0;
}