C library functions -signal()

C Standard Library - <signal.h>

Description

C Library Functionsvoid (*signal(int sig, void (*func)(int)))(int)Set up a function to handle the signal, i.e., withsigThe signal handler for the parameter.

signalThe function is a function in the C standard library, used to set up signal handlers. It is defined in<signal.h>In the header file.signalThe function allows a program to define, when certain signals (such asSIGINT, generated by pressing Ctrl+C) arrive, the handler to be executed.

Declaration

Below is the declaration of the signal() function.

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

Parameter

  • sig-- The signal code used as a variable in the signal handler. Here are some important standard signal constants:
Macrosignal
SIGABRT(Signal Abort) Program terminated abnormally.
SIGFPE(Signal Floating-Point Exception) Arithmetic operation error, such as divisor being 0 or overflow (not necessarily a floating-point operation).
SIGILL(Signal Illegal Instruction) Illegal function image, such as an illegal instruction, usually caused by a variant in the code or an attempt to execute data.
SIGINT(Signal Interrupt) Interrupt signal, such as ctrl-C, usually generated by the user.
SIGSEGV(Signal Segmentation Violation) Illegal memory access, such as accessing a non-existent memory unit.
SIGTERM(Signal Terminate) The termination request signal sent to this program.
  • func-- A pointer to a function. It can be a function defined by the program, or one of the following predefined functions:
SIG_DFLThe default signal handler.
SIG_IGNIgnore the signal.

Return Value

This function returns the previous value of the signal handler; when an error occurs, it returns SIG_ERR.

Example

The following example demonstrates the usage of the signal() function.

Example

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

void sighandler(int);

int main()
{
   signal(SIGINT, sighandler);

   while(1)
   {
      printf(Start sleeping for one second...\n");
      sleep(1);
   }

   return(0);
}

void sighandler(int signum)
{
   printf(Catch signal %d, jump out...\n", signum);
   exit(1);
}

Let us compile and run the above program, which will produce the following results, and the program will enter an infinite loop, requiring the use of CTRL + C to break out of the program.

开始休眠一秒钟...
开始休眠一秒钟...
开始休眠一秒钟...
开始休眠一秒钟...
开始休眠一秒钟...
捕获信号 2,跳出...

C Standard Library - <signal.h>

other extensions