Linux 中的 Ctrl + C 中断事件处理 [英] Ctrl + C interrupt event handling in Linux

查看:52
本文介绍了Linux 中的 Ctrl + C 中断事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 C++ 并使用 Linux GNU C 编译器编译的应用程序.

I am developing an application that uses C++ and compiles using Linux GNU C Compiler.

当用户使用 Ctrl + C 键中断脚本时,我想调用一个函数.

I want to invoke a function as the user interrupts the script using Ctrl + C keys.

我该怎么办?任何答案将不胜感激.

What should I do? Any answers would be much appreciated.

推荐答案

当你按下 Ctr + C 时,操作系统会发送一个 向进程发送信号.有很多信号,其中之一是 SIGINT.SIGINT(程序中断")是终止信号之一.

When you press Ctr + C, 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 的默认操作是程序终止.也就是说,如果您的程序没有专门处理此信号,则当您按 Ctr + C 时,您的程序将作为默认操作终止.

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 Ctr + C 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

  1. 信号(int signum, sighandler_t handler);
  2. 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 执行它.代码中有一个无限循环,它将一直运行,直到您通过按 Ctr + C 发送 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 Ctr + C.

这篇关于Linux 中的 Ctrl + C 中断事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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