Search code examples
clinuxsignals

Handle a kill signal


I want to handle a kill signal from C program. I'm starting by create an infinite loop and handle the signal

void signal_callback_handler(int signum)
{
   printf("Caught signal %d\n",signum);
   // Cleanup and close up stuff here

   // Terminate program
   exit(signum);
}
 main()
{
    signal(SIGINT, signal_callback_handler);
    printf("pid: %d \n",getpid());
    while(1)
    {

    }

}

When I run this program and make CTRL+C, the kill is handled, and it works. The message Caught signal is printed. However, when I'm trying to kill from another program

int main(int argc, char **argv)
{
    kill(atoi(argv[1]), SIGKILL);

    return 0;

}

The program is stoped but the signal is not handled. In other words, the message Caught signal is not printed. The infinite loop is just stopped.


Solution

  • This is it: you cannot catch a SIGKILL, it will definitely kill your program, this is what it's been created for.