C++ 如何使用sigaction()截取SIGINT?
我试图修改以下代码以使用sigaction()拦截SIGINT 我需要将“for”循环替换为“while(1);您应该能够通过输入“^\”退出程序(需要拦截SIGQUIT)C++ 如何使用sigaction()截取SIGINT?,c++,operating-system,signals,C++,Operating System,Signals,我试图修改以下代码以使用sigaction()拦截SIGINT 我需要将“for”循环替换为“while(1);您应该能够通过输入“^\”退出程序(需要拦截SIGQUIT) #包括 #包括 #包括 使用名称空间std; 无效函数(内部信号) { cout您可以使用sigaction捕获SIGINT(并且仍然有您描述的输出)和以下代码(在类似Unix的操作系统上使用clang编译并为我工作): #包括 #包括 #包括 静态int=0; 静态无效信号发生器(内部信号) { sig=signum; }
#包括
#包括
#包括
使用名称空间std;
无效函数(内部信号)
{
cout您可以使用sigaction
捕获SIGINT
(并且仍然有您描述的输出)和以下代码(在类似Unix的操作系统上使用clang编译并为我工作):
#包括
#包括
#包括
静态int=0;
静态无效信号发生器(内部信号)
{
sig=signum;
}
int main()
{
int signum=SIGINT;
结构sigaction newact;
结构信号动作;
newact.sa_handler=sighandler;
sigemptyset(和newact.sa_面具);
newact.sa_标志=0;
sigaction(signum、newact和oldact);
而(!被抓住)
{
std::cout SIGINT或SIGQUIT?是哪一个?需要使用正确的信息设置struct sigaction
变量。然后调用sigaction()
而不是signal()
。其余大部分保持不变。请注意,调用cout
#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;
}
#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;
}