C signal()

signal() 函数在 signal.h 头文件中定义。它有助于处理带信号编号的信号。


void (*signal(int sig, void (*func)(int)))(int); #where sig should be in integer

 

signal() 参数

signal() 函数以信号编号和函数作为其参数。一些重要的标准信号编号如下。

  • SIGABRT:异常终止,例如由函数启动的终止。
  • SIGFPE:错误的算术操作,例如除零或导致溢出的操作。
  • SIGILL:无效的函数映像,例如非法指令。
  • SIGINT:交互式注意信号。通常由应用程序用户生成。
  • SIGSEGV:无效的存储访问——当程序试图读写其分配内存之外的区域时。
  • SIGTERM:发送给程序的终止请求。

以下是预定义的函数

  • SIG_DFL:默认处理——信号由该特定信号的默认操作处理。
  • SIG_IGN:忽略信号——信号被忽略。
参数 描述 必需/可选
sig 将处理函数设置为的信号编号。 必需
func 这是一个指向函数的指针。这可以是程序员定义的函数。 必需

signal() 返回值

signal() 函数返回上一个信号处理程序的值,如果出错则返回 SIG_ERR。

输入 返回值
如果参数 信号处理程序的值

signal() 示例

示例 1:C 语言中 pow() 函数的工作原理?


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int main () {
   signal(SIGINT, handler);

   while(1) {
      printf("Going to sleep for a second...\n");
      sleep(1); 
   }
   return(0);
}

void handler(int SNo) {
   printf("Caught signal %d, coming out...\n", SNo);
   exit(1);
}

输出


Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Caught signal 2, coming out...

示例 2:C 语言中 signal() 函数的工作原理?


#include <stdio.h>
#include <signal.h>
int main()
{
    signal(SIGINT, handle_sigint);
    while (1)
    {
        printf(“signal processing\n”);
        sleep(1);
    }
    return 0;
}

输出


signal processing   
signal processing        
signal processing      
terminated