我正在尝试以下信号处理程序,引用在线教程,但它似乎不起作用,我的代码有什么问题:
#include<signal.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
typedef void (*SignalHandlerPointer)(int);
static void UsrHostSigAbort(int pSignal)
{
//stopService();
printf("pankaj");
}
void HandleHostSignal()
{
struct sigaction satmp;
memset(&satmp, '\0' , sizeof(satmp));
SignalHandlerPointer usrSigHandler;
satmp.sa_flags &= ~SA_SIGINFO;
satmp.sa_handler = UsrHostSigAbort;
usrSigHandler = sigaction (SIGINT , &satmp, NULL);
}
void main()
{
HandleHostSignal();
while(1)
{
sleep(1);
}
}
我正在 ubuntu 中编译并运行这个程序。
最佳答案
此代码(基本上只是代码的一个简单变体)可以在 macOS Sierra 10.12.1 上正确运行:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static void UsrHostSigAbort(int pSignal)
{
// stopService();
// Using printf is not good - see: http://stackoverflow.com/questions/16891019/
// It will suffice for this code, however.
printf("pankaj %d\n", pSignal);
}
static void HandleHostSignal(void)
{
struct sigaction satmp;
sigemptyset(&satmp.sa_mask);
satmp.sa_flags = 0;
satmp.sa_handler = UsrHostSigAbort;
sigaction(SIGINT, &satmp, NULL);
}
int main(void)
{
HandleHostSignal();
while (1)
{
sleep(1);
putchar('.');
fflush(stdout);
}
}
示例输出(名为 sig19
的程序):
$ ./sig19
......^Cpankaj 2
.....^Cpankaj 2
....^Cpankaj 2
...^Cpankaj 2
..^Cpankaj 2
.^Cpankaj 2
..................^\Quit: 3
$
我使用退出键(终端上的^\
)来停止程序。
关于c - 为什么我的信号处理程序无法使用 sigaction 函数工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40231565/