当程序用ctrl c结束时调用一个函数 [英] call a function when the program is finished with ctrl c

查看:148
本文介绍了当程序用ctrl c结束时调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux环境下工作,我有一个C ++程序,我想要的是当我用ctrl + c取消程序时,我希望程序执行一个函数,关闭一些文件并打印一些sutff,有没有办法做到这一点?谢谢。

解决方案

signal()在Linux上支持 sigaction()signal versus sigaction



这是我最近碰到的一个例子(点击中断信号),并随着我玩弄它而进行修改。

 #include< stdio.h中> 
#include< unistd.h>
#include
#include< string.h>

struct sigaction old_action;

void sigint_handler(int sig_no)
{
printf(CTRL-C pressed \\);
sigaction(SIGINT,& old_action,NULL);
kill(0,SIGINT);
}

int main()
{

struct sigaction action;
memset(& action,0,sizeof(action));
action.sa_handler =& sigint_handler;
sigaction(SIGINT,& action,&old_action);

pause();

返回0;
}


I am working in the Linux environment, and I have a C++ program, what I want is when I cancel the program with ctrl+c I would like that the program executes a function, to close some files and print some sutff, is there any way to do this?. Thank you.

解决方案

signal() can be dangerous on some OSes and is deprecated on Linux in favor of sigaction(). "signal versus sigaction"

Here's an example that I ran across recently ("Tap the interrupt signal") and modified as I was playing around with it.

#include<stdio.h>
#include<unistd.h>
#include<signal.h>
#include<string.h>

struct sigaction old_action;

void sigint_handler(int sig_no)
{
    printf("CTRL-C pressed\n");
    sigaction(SIGINT, &old_action, NULL);
    kill(0, SIGINT);
}

int main()
{

    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = &sigint_handler;
    sigaction(SIGINT, &action, &old_action);

    pause();

    return 0;
}

这篇关于当程序用ctrl c结束时调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆