catching all signals in linux

会有一股神秘感。 提交于 2021-02-07 19:01:48

问题


I'm trying to write a process in C/linux that ignores the SIGINT and SIGQUIT signals and exits for the SIGTERM. For the other signals it should write out the signal and the time. I'm having trouble cathing all the signals because i'm familiar only with catching 1 signal. If anyone could help me with this I'd appreciate it very much. Here is my code:

#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;
}

回答1:


Here is the easy way

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

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

and so on.

signal() and sighandler() is the least complicated way to do this.

Call signal for each signal that you want to catch. But as some have said earlier you can only catch certain signals. Best to have a way to gracefully shut the program down.



来源:https://stackoverflow.com/questions/19618579/catching-all-signals-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!