Latest web development tutorials

C library functions - signal ()

C standard library - <signal.h> C standard library - <signal.h>

description

C library functionvoid (* signal (int sig, void (* func) (int))) (int) to set up a function to process the signal with a signal handler that is sigparameters.

statement

The following is a statement signal () function.

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

parameter

  • sig - signal codes in the signal processing used in the program as a variable.Here are some important criteria signal constants:
信号
SIGABRT(Signal Abort) 程序异常终止。
SIGFPE(Signal Floating-Point Exception) 算术运算出错,如除数为 0 或溢出(不一定是浮点运算)。
SIGILL(Signal Illegal Instruction) 非法函数映象,如非法指令,通常是由于代码中的某个变体或者尝试执行数据导致的。
SIGINT(Signal Interrupt) 中断信号,如 ctrl-C,通常由用户生成。
SIGSEGV(Signal Segmentation Violation) 非法访问存储器,如访问不存在的内存单元。
SIGTERM(Signal Terminate) 发送给本程序的终止请求信号。
  • func - a pointer to a function.It can be a function defined by the program, it can be one of the predefined function below:
SIG_DFL默认的信号处理程序。
SIG_IGN忽视信号。

return value

This function returns the value of the signal handler before the return SIG_ERR when an error occurs.

Examples

The following example illustrates the signal () function is used.

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

void sighandler(int);

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

   while(1) 
   {
      printf("开始休眠一秒钟...\n");
      sleep(1);
   }

   return(0);
}

void sighandler(int signum)
{
   printf("捕获信号 %d,跳出...\n", signum);
   exit(1);
}

Let's compile and run the above program, which will produce the following results, and the program will enter an infinite loop, use the CTRL + C keys out of the program.

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

C standard library - <signal.h> C standard library - <signal.h>