0

Hi i've done this code but there are somethings i need to add like.

  1. ignore signal SIGINT
  2. restore the signal handler for SIGINT to the default one
  3. catch signal SIGINT and prints out the numerical value of the signal

so far this is the coding i have

      void sig_handler(int signo)
    {
    // body of signal handler
    }

    int main()
{
    struct sigaction act;
    act.sa_flags = 0;
    act.sa_handler = sig_handler;
    sigfillset( & (act.sa_mask) );

if (sigaction(sig, &act, NULL) != 0) 
    {
         perror("sigaction"); exit(1);
    }
}
Blair
  • 1
  • 3
  • And the question is? – alk Apr 14 '17 at 10:17
  • Do you want to write a code that catches SIGINT and prints its numerical value? Do you want to do anything more that this? Refer [this](http://stackoverflow.com/questions/4217037/catch-ctrl-c-in-c) for a hint on how to write a code. – Gaurav Pathak Apr 14 '17 at 10:23

1 Answers1

0

Something like this will get you started.

#include <stdio.h>
#include <signal.h>

void    handle_signal(int signum)
{
    printf("\nRecived signal: %d\n", signum);
    switch(signum)
    {
        case SIGINT:
            printf("I won't respond to ctrl-c!\n");

            //restore to default
            signal(SIGINT, SIG_DFL);
            break;
        case SIGWINCH:
            //windows size change
            break;
        case SIGCONT:
            //continue process 'fg' in terminal
            break;
        case SIGTSTP:
            //ctrl-z
            break;
        default:
            //others
            break;
    }
}

void        listen_to_signals(void)
{
    int     i;

    i = 0;
    while (i < 32)
    {
        if (i != SIGKILL && i != SIGSTOP && i != SIGCHLD && i != SIGCONT &&
            i != SIGURG && i != SIGIO)
            signal(i, &handle_signal);
        i++;
    }
}

int     main()
{
    listen_to_signals();
    while(1)
    {}
}

Note, I'm listening to all signals I can: there are some signals that I can't listen to (like kill).

Note: use 'kill -9 pidof your_program' to stop it

Note: the first time SIGINT will be ignored, but the second time, it won't (because I'm restoring it to its default behavior)

Emil Terman
  • 526
  • 4
  • 22