Pejman Moghadam / C-programming

C - Catching Signals

Public Domain


Catching SIGALRM and SIGINT Signals

/* signal-catch.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h> 

void catcher(int signum)
{
    if (signum == SIGALRM) {
            printf("SIGALRM \n");
            return;
    } else if (signum == SIGINT) {
            printf("SIGINT \n");
            exit(-1);
    }
}

int main()
{
    struct sigaction act;

    memset(&act, 0, sizeof(act));
    act.sa_handler = &catcher;
    sigaction(SIGALRM, &act, NULL);
    sigaction(SIGINT, &act, NULL);
    for (;;)
            sleep(1);
    return 0;
}

Compile and Run

gcc signal-catch.c -o signal-catch
./signal-catch

Test

ps -A | grep signal-catch
kill -s SIGALRM 30506 
kill -s SIGALRM 30506 
kill -s SIGALRM 30506 
kill -s SIGINT  30506

BY: Pejman Moghadam
TAG: c, signal
DATE: 2014-01-15 12:01:10


Pejman Moghadam / C-programming [ TXT ]