繁体   English   中英

在Linux中捕获所有信号

[英]catching all signals in linux

我正在尝试在C / linux中编写一个进程,该进程将忽略SIGINT和SIGQUIT信号并退出SIGTERM。 对于其他信号,应写出信号和时间。 我在收集所有信号时遇到麻烦,因为我只熟悉捕获1个信号。 如果有人可以帮助我,我将非常感激。 这是我的代码:

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

int done = 0;

void term(int signum)
{
    if (signum == 15)
    {   
        //printf("%d\n",signum);        
        printf("Received SIGTERM, exiting ... \n");
        done  = 1;
    }
    else
    {
        time_t mytime = time(0);
        printf("%d: %s\n", signum, asctime(localtime(&mytime)));
        printf("%d\n",signum);
    }
}

int main(int argc, char *argv[])
{
    struct sigaction action;
    memset(&action, 0, sizeof(struct sigaction));
    action.sa_handler = term;
    sigaction(SIGTERM, &action, NULL);
    struct sigaction act;
    memset(&act, 0, sizeof(struct sigaction));
    act.sa_handler = SIG_IGN;
    sigaction(SIGQUIT, &act, NULL);
    sigaction(SIGINT, &act, NULL);

    int loop = 0;
    while(!done)
    {
        sleep(1);
    }

    printf("done.\n");
    return 0;
}

这是简单的方法

void sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
}   

int main(void)
{
       if (signal(SIGINT, sig_handler) == SIG_ERR)

等等。

signal()和sighandler()是执行此操作最简单的方法。

您要捕获的每个信号的呼叫信号。 但是正如某些人之前所说,您只能捕获某些信号。 最好有一种方法可以正常关闭程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM