Tuesday, April 19, 2016

Linux, how do signal use?

This example explain how do linux signal use sum calls.
Written signal handler function register signals and define behavior signals.
This example use two signals, SIGINT and SIGTSTP.

Program compiling.
$ gcc signal.c -o signal

Program running.
$ ./signal
I'm working...
^CCatch SIGNAL[2]    <-- Ctrl + c key in.
Work harder!              <-- Signal handler message. Don’t stop.
I'm working...
I'm working...
^ZCatch SIGNAL[20]   <-- Ctrl + z key in.
We have a break.        <-- Signal handler message. It’s goiung stop.
I've had enough!
$

signal.c

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>

static void signalHandler(int sig) ;

static int  doit;

int main(int argc, char** argv) {

    struct sigaction   act;

    act.sa_handler = &signalHandler;
    act.sa_flags = 0;
    sigfillset(&act.sa_mask);

    if (sigaction(SIGINT, &act, NULL)<0) {
        perror("SIGINT sigaction()");
        exit(-1);
    }
    if (sigaction(SIGTSTP, &act, NULL)<0) {
        perror("SIGTSTP sigaction()");
        exit(-1);
    }

    doit = 1;

    while(doit) {
        printf("I'm working...\n");
        sleep(1);
    }

    printf("I've had enough!\n");
    return(0);
}

static void signalHandler(int sig) {

    printf("Catch SIGNAL[%d]\n", sig);

    switch(sig) {
        case SIGINT:
            printf("Work harder!\n");
            break;
        case SIGTSTP:
            printf("We have a break.\n");
            doit = 0;         // Quit process working
            break;
        default:
            printf("I don't know.\n");
    }
}


No comments:

Post a Comment