c - 为什么我的信号处理程序无法使用 sigaction 函数工作?

标签 c signals sigint

我正在尝试以下信号处理程序,引用在线教程,但它似乎不起作用,我的代码有什么问题:

#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/

相关文章:

c - pthread_sigmask 干扰 GDB

c++ - 如何使用嵌套在没有名称的结构中的c union

c - 特定应用程序无法识别 DLL 入口点

node.js - Node : Send Ctrl+C to a child process on Windows

python - 在缓慢的系统调用中处理 SIGINT

c - 在循环中使用 scanf 处理 SIGINT

c - 在 C 中使用 Union 设置位

c - 8 个皇后拼图 : using random numbers causes infinite loop

matlab - Matlab中的音频信号处理

c - 当我按下键 a 时将传递什么值