catching all signals in linux

12,218

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.

Share:
12,218
spd92
Author by

spd92

Updated on June 04, 2022

Comments

  • spd92
    spd92 almost 2 years

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