What Is Dead May Never Die

Let's have some fun with the Drowned God and Unix signals.

This is a simple program that catches SIGINT and SIGTERM

#include <stdio.h>  // for printf() && perror()
#include <stdlib.h> // for exit()
#include <signal.h> // for all the signal fun
#include <unistd.h> // for sleep()

/**
 * catch signals
 */
void catch(int sig)
{
    static int counter = 0;

    // prevent exit by SIGINT and SIGTERM 3 times and then exit program
    if (sig == SIGINT || sig == SIGTERM) {
        if (counter < 3) {
            printf("What is dead may never die\n");
            counter += 1;
        } else {
            printf("Okay... :(\n");
            exit(0);
        }
    }
}

int main(int ac, char ** av)
{
    // set catcher for the interrupt signal
    if (signal(SIGINT, catch) == SIG_ERR) {
        perror("Can't catch SIGINT\n");
    }

    // set catcher for the kill signal
    if (signal(SIGTERM, catch) == SIG_ERR) {
        perror("Can't catch SIGTERM\n");
    }

    printf("We do not sow\n");

    // keep running in background, we exit by other means
    while(1) {
        sleep(1);
    }
}

Compile it and run, then try to kill all Greyjoy :)

$ clang -o greyjoy greyjoy.c
$ ./greyjoy &
[1] 31366
We do not sow
$ killall greyjoy
What is dead may never die
$ killall greyjoy
What is dead may never die
$ killall greyjoy
What is dead may never die
$ killall greyjoy
Okay... :(
[1]+  Done                    ./greyjoy
$

It seems they are somehow protected :)

A good example of signals handling can be found here: www.thegeekstuff.com

Comments

Comments powered by Disqus