/*
 *
 * Whenever you do kill -9, you kill a process without giving it
 * a chance to perform cleanup duties or sync state to disk.
 *
 * kill -15 (SIGTERM) is safer, it is also the default.
 *
 */

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

/* The flag used to signal that a SIGTERM has been recieved */
volatile sig_atomic_t sigterm = 0;

/* The handler that modifes the flag once the signal is recieved */
void handler(int);

void
handler(int sig)
{
    sigterm = 1;
}

int
main(int argc, char *argv[])
{
    /* Connect the signal to the handler */
    signal(SIGTERM, handler);

    /* The program does it's thing forever */
    for(;;)
    {
        printf("Doing my thing...\n");
        sleep(1);

        /* If the signal has been recieved it is time to shut down */
        if (sigterm) {
            /* Perform whatever cleanup or syncing that needs to be done */
            printf("Received SIGTERM, exiting loop...\n");
            break;
        }
    }

    printf("Program completed properly!\n");
    return 0;
}