signal function(Install Signal Handler) in C Language – example and detail

In the C Programming Language, the signal feature installs a feature as the handler for a signal.

Syntax

The syntax for the signal characteristic in the C Language is:

void (*signal(int sig, void (*func)(int)))(int);

Parameters or Arguments

sig The numeric fee of the signal. func The feature to set up as the sign handler.

Returns

The signal feature returns a pointer to the preceding handler for this signal. If the handler can now not be installed, the signal feature returns SIG_ERR.

Required Header

In the C Language, the required header for the sign characteristic is:

#include <signal.h>

Applies To

In the C Language, the signal function can be used in the following versions:

ANSI/ISO 9899-1990

signal Example

/* Example using signal by TechOnTheNet.com */

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

void signal_handler(int signal)
{
    /* Display a message indicating we have received a signal */
    if (signal == SIGUSR2) printf("Received a SIGUSR2 signal\n");

    /* Exit the application */
    exit(0);
}

int main(int argc, const char * argv[])
{
    /* Display a message indicating we are registering the signal handler */
    printf("Registering the signal handler\n");

    /* Register the signal handler */
    signal(SIGUSR2, signal_handler);

    /* Display a message indicating we are raising a signal */
    printf("Raising a SIGUSR2 signal\n");

    /* Raise the SIGUSR2 signal */
    raise(SIGUSR2);

    /* Display a message indicating we are leaving main */
    printf("Finished main\n");

    return 0;
}

When compiled and run, this application will output:

Registering the signal handler
Raising a SIGUSR2 signal
Received a SIGUSR2 signal

See Also

Other C features that are noteworthy when dealing with the sign function:

abort characteristic raise characteristic