在命令窗口中按下ctrl+c后 程序虽然停止运行,但不能退出到命令行状态,必须强制退出才可以。 添加了signal(SIGINT, MySigintHandler);但不能自动调用

问题描述:
在命令窗口中按下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);
}

参考:
https://www.cnblogs.com/HaoQChen/p/11048616.html

原文链接:https://blog.csdn.net/ABC_ORANGE/article/details/105096782

官网资料:官方文档-Initialization and Shutdown

一定要加头文件:#include <signal.h>

猜你喜欢

转载自blog.csdn.net/jianlai_/article/details/128105892