A Simple Linux Signal Example

I studied about utilizing signals offered by Linux operating system. It allows you to make an event-driven program. You can overwrite the default behavior of Ctrl+C in your program to do something else instead of killing the program.I find it easy and very straightforward. I will give an example here and explanation in the next post.

An this is my inspiration.

And this is the example.

// Hey apple - Linux signal programming example
#include <stdio.h>
#include <signal.h>

unsigned int count_sigint = 0;

void my_sigaction_handler(int signum, siginfo_t* siginfo, void* ucontext) {
    printf("Hey, midget apple!\n");
    count_sigint++;
}

int main(int argc, char* argv[]) {
    struct sigaction my_sigaction;
    my_sigaction.sa_handler = SIG_DFL;
    // Defines a signal handling function for my_sigaction
    my_sigaction.sa_sigaction = my_sigaction_handler;
    sigfillset(&my_sigaction.sa_mask);
    my_sigaction.sa_flags = SA_SIGINFO;
    // Ctrl + c fires SIGINT signal. 
    // Overwrite SIGINT handling behavior by my_sigaction
    sigaction(SIGINT, &my_sigaction, NULL);
    while (count_sigint < 5) {
        printf("Hey, apple!\n");
        sleep(1);
    }
    return 0;
}

I think you can guess what this program does. Yes! It keeps saying “Hey, apple!” “Hey, apple!”. And, when you tries to stop it (by pressing Ctrl + c), it says “Hey, midget apple!”. Sadly, it says this for only 5 times. You know what would happen if it does not. Here was my run output.

fulcronz27@alaptop:~/Documents/heyapple$ clear
fulcronz27@alaptop:~/Documents/heyapple$ gcc main.c -o heyapple.o
fulcronz27@alaptop:~/Documents/heyapple$ ./heyapple.o
Hey, apple!
Hey, apple!
Hey, apple!
Hey, apple!
Hey, apple!
Hey, midget apple
Hey, apple!
Hey, midget apple
Hey, apple!
Hey, midget apple
Hey, apple!
Hey, apple!
Hey, midget apple
Hey, apple!
Hey, midget apple
pipatmet@alaptop:~/Documents/heyapple$

This can be a boilerplate for you to implement signal handling in your future programs.

Advertisements

One thought on “A Simple Linux Signal Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s