如何使用 sigaction() 拦截 SIGINT
How can i use sigaction() to intercept SIGINT?
我正在尝试修改以下代码以使用 sigaction() 拦截 SIGINT;
我需要将"for"循环替换为"while ( 1 );您应该能够通过输入"^\"退出程序。(需要拦截SIGQUIT。
#include <signal.h>
#include <unistd.h>
#include <iostream>
using namespace std;
void func ( int sig )
{
cout << "Oops! -- I got a signal " << sig << endl;
}
int main()
{
(void) signal ( SIGINT, func ); //catch terminal interrupts
//for ( int i = 0; i < 20; ++i )
while(1)
{
cout << "signals" << endl;
sleep ( 1 );
}
return 0;
}
您可以使用sigaction
使用以下代码(在类似操作系统的Unix上使用clang编译和工作)来捕获SIGINT
(并且仍然具有您描述的输出):
#include <signal.h>
#include <iostream>
#include <unistd.h>
static int sigcaught = 0;
static void sighandler(int signum)
{
sigcaught = signum;
}
int main()
{
int signum = SIGINT;
struct sigaction newact;
struct sigaction oldact;
newact.sa_handler = sighandler;
sigemptyset(&newact.sa_mask);
newact.sa_flags = 0;
sigaction(signum, &newact, &oldact);
while (!sigcaught)
{
std::cout << "waiting for signal" << std::endl;
sleep(1);
}
std::cout << "Oops! -- I got a signal " << sigcaught << std::endl;
return 0;
}
请注意:此代码故意不检查返回值(例如来自sigaction
或sleep
),因为原始代码不是,并且检查它们可能会分散读者看到相关差异的注意力。但是,我不希望生产代码忽略返回值(尤其是那些可以指示错误的值)。
相关文章:
- boost::asio 无法捕获 SIGINT
- 脚本中缺少SIGINT?
- Visual C++ Win32 API 代码来拦截某个击键
- 拖放我的MDI被CRichEditView拦截并在CRichEditView::GetDocument中崩溃 - 如何覆
- 如何使用 SIGINT 在第二个线程中断 getchar
- 如何在C++中正确创建/实现拦截器库?
- 使用eBPF拦截Linux上的所有传出/传入流量
- 调用系统(3)时忽略了SIGINT
- 如何拦截所有对 AfxThrowMemoryException 的调用
- 加密前如何拦截应用通信?
- 是否可以拦截/检测关闭 PC 并首先执行操作的请求?
- 在 SIGINT 上优雅地关闭
- 在接收 SIGINT 操作时适当地关闭多线程 c++ 应用程序
- 如何拦截Qt Quick qml事件
- C++ grpc::experimental:interceptor 如何从自定义拦截器返回状态和消息
- 在线编译器 - 等待输入并自动馈送输入时拦截程序
- JNI 本机静态方法拦截
- 拦截黑莓电话
- 程序结构以捕获SIGINT并在C++中调用析构函数
- 如何使用 sigaction() 拦截 SIGINT