totn C Functions

C Language: signal function
(Install Signal Handler)

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

Syntax

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

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

Parameters or Arguments

sig
The numeric value of the signal.
func
The function to install as the signal handler.

Returns

The signal function returns a pointer to the previous handler for this signal. If the handler can not be installed, the signal function returns SIG_ERR.

Required Header

In the C Language, the required header for the signal function 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 functions that are noteworthy when dealing with the signal function: