轉(zhuǎn):https://haoqchen.site/2018/04/28/ROS-node-init/
很多ROS新手編寫節(jié)點的時候都不知道要怎么才能Ctrl+c退出,根本都沒有注意到一個節(jié)點的生命流程,看完你就懂了~~
#include "ros/ros.h" #include <signal.h> void MySigintHandler(int sig) { //這里主要進行退出前的數(shù)據(jù)保存、內(nèi)存清理、告知其他節(jié)點等工作 ROS_INFO("shutting down!"); ros::shutdown(); } int main(int argc, char** argv){ //ros::init() /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "ist_node"); //初始化節(jié)點名字必須在最前面,如果ROS系統(tǒng)中出現(xiàn)重名,則之前的節(jié)點會被自動關閉 //如果想要多個重名節(jié)點而不報錯,可以在init中添加ros::init_options::AnonymousName參數(shù) //該參數(shù)會在原有節(jié)點名字的后面添加一些隨機數(shù)來使每個節(jié)點獨一無二 //ros::init(argc, argv, "my_node_name", ros::init_options::AnonymousName); //ros::NodeHandle /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will call ros::shutdown() to close down the node. */ ros::NodeHandle h_node; //獲取節(jié)點的句柄,init是初始化節(jié)點,這個是Starting the node //如果不想通過對象的生命周期來管理節(jié)點的開始和結(jié)束,你可以通過ros::start()和ros::shutdown() 來自己管理節(jié)點。 ros::Rate loop_rate(1); //loop once per second //Cannot use before the first NodeHandle has been created or ros::start() has been called. //shut down signal(SIGINT, MySigintHandler); //覆蓋原來的Ctrl+C中斷函數(shù),原來的只會調(diào)用ros::shutdown() //為你關閉節(jié)點相關的subscriptions, publications, service calls, and service servers,退出進程 //run status int sec = 0; while(ros::ok() && sec++ < 5){ loop_rate.sleep(); ROS_INFO("ROS is ok!"); ros::spinOnce(); } //ros::ok()返回false,代表可能發(fā)生了以下事件 //1.SIGINT被觸發(fā)(Ctrl-C)調(diào)用了ros::shutdown() //2.被另一同名節(jié)點踢出 ROS 網(wǎng)絡 //3.ros::shutdown()被程序的另一部分調(diào)用 //4.節(jié)點中的所有ros::NodeHandles 都已經(jīng)被銷毀 //ros::isShuttingDown():一旦ros::shutdown()被調(diào)用(注意是剛開始調(diào)用,而不是調(diào)用完畢),就返回true //一般建議用ros::ok(),特殊情況可以用ros::isShuttingDown() ROS_INFO("Node exit"); printf("Process exit\n"); return 0; }
浙公網(wǎng)安備 33010602011771號