問題描述:
在命令窗口中按下ctrl+c後 程序雖然停止運行,但不能退出到命令行狀態,必須強制退出纔可以。 添加了signal(SIGINT, MySigintHandler);但不能自動調用
解決辦法:
signal(SIGINT, MySigintHandler);添加的位置不正確。調整在程序中的位置如下所示:放到ros::Rate 和 ros::NodeHandle nh; 語句後面就可以了。
int main(int argc, char** argv)
{
ros::init(argc, argv, "test");
ros::AsyncSpinner spinner(4);
ros::NodeHandle nh;
ros::Rate rate(30);
spinner.start();
signal(SIGINT, MySigintHandler);
//覆蓋原來的Ctrl+C中斷函數,原來的只會調用ros::shutdown(),按下了Ctrl+C,則會調用MySigintHandler
//爲你關閉節點相關的subscriptions, publications, service calls, and service servers,退出進程
while(ros::ok)
{
//code
}
return 0;
}
MySigintHandler代碼如下:
void MySigintHandler(int sig)
{
//這裏主要進行退出前的數據保存、內存清理、告知其他節點等工作
ROS_INFO("shutting down!");
ros::shutdown();
exit(0);
}