问题描述
我正在开发一个使用 C++ 并使用 Linux GNU C 编译器编译的应用程序.
I am developing an application that uses C++ and compiles using Linux GNU C Compiler.
当用户使用 + 键中断脚本时,我想调用一个函数.
I want to invoke a function as the user interrupts the script using + keys.
我该怎么办?任何答案将不胜感激.
What should I do? Any answers would be much appreciated.
推荐答案
当你按下 时,操作系统会发送一个 向进程发送信号.有很多信号,其中之一是 SIGINT.SIGINT(程序中断")是终止信号之一.
When you press , the operating system sends a signal to the process. There are many signals and one of them is SIGINT. The SIGINT ("program interrupt") is one of the Termination Signals.
还有更多种类的终止信号,但 SIGINT 的有趣之处在于它可以被您的程序处理(捕获).SIGINT 的默认操作是程序终止.也就是说,如果您的程序没有专门处理此信号,则当您按 时,您的程序将作为默认操作终止.
There are a few more kinds of Termination Signals, but the interesting thing about SIGINT is that it can be handled (caught) by your program. The default action of SIGINT is program termination. That is, if your program doesn't specifically handle this signal, when you press your program terminates as the default action.
要更改信号的默认操作,您必须注册要捕获的信号.在 C 程序中注册一个信号(至少在 POSIX 系统下)有两个函数
To change the default action of a signal you have to register the signal to be caught. To register a signal in a C program (at least under POSIX systems) there are two functions
- 信号(int signum, sighandler_t handler);
- sigaction(int signum, const struct sigaction *act,结构 sigaction *oldact);.
这些函数需要将标头 signal.h 包含在您的 C 代码中.我在下面提供了一个带有注释的 signal
函数的简单示例.
These functions require the header signal.h to be included in your C code. I have provide a simple example of the signal
function below with comments.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h> // our new library
volatile sig_atomic_t flag = 0;
void my_function(int sig){ // can be called asynchronously
flag = 1; // set flag
}
int main(){
// Register signals
signal(SIGINT, my_function);
// ^ ^
// Which-Signal |-- which user defined function registered
while(1)
if(flag){ // my action when signal set it 1
printf("
Signal caught!
");
printf("
default action it not termination!
");
flag = 0;
}
return 0;
}
注意:您应该只调用 安全/授权函数在信号处理程序中.例如 避免在信号处理程序中调用 printf一个>.
Note: you should only call safe/authorized functions in signal handler. For example avoid calling printf in signal handler.
您可以使用 gcc 编译此代码并从 shell 执行它.代码中有一个无限循环,它将一直运行,直到您通过按 发送 SIGINT
信号.
You can compile this code with gcc and execute it from the shell. There is an infinite loop in the code and it will run until you send a SIGINT
signal by pressing .
这篇关于Linux 中的 Ctrl + C 中断事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!