用ctrl c完成程序时调用一个函数

Edu*_*rdo 5 linux function

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

Mr.*_*rat 8

signal()在某些操作系统上可能会有危险,在Linux上也不赞成使用sigaction()."信号与sigaction"

这是我最近遇到的一个例子("点击中断信号")并在我玩它的时候进行了修改.

#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;
}
Run Code Online (Sandbox Code Playgroud)


Jay*_*Jay 7

有关完整的工作示例,您可以尝试以下代码:

#include <signal.h>
#include <stdio.h>
#include <stdbool.h>

volatile bool STOP = false;
void sigint_handler(int sig);

int main() {
    signal(SIGINT, sigint_handler);
    while(true) {
        if (STOP) {
            break;
        }
    }
    return 0;
}

void sigint_handler(int sig) {
    printf("\nCTRL-C detected\n");
    STOP = true;
}
Run Code Online (Sandbox Code Playgroud)

示例运行:

[user@host]$ ./a.out 
^C
CTRL-C detected
Run Code Online (Sandbox Code Playgroud)