位置:首頁 > 高級語言 > C語言標準庫 > signal() - C函數

signal() - C函數

C庫函數 void (*signal(int sig, void (*func)(int)))(int)設置一個函數來處理信號,即信號數量sig的信號處理程序 。

聲明

以下是signal()函數的聲明。

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

參數

  • sig -- 這是信號的處理功能被設置的號碼。以下是幾個重要的標準信號的數字:

macro signal
SIGABRT (Signal Abort) Abnormal termination, such as is initiated by the function.
SIGFPE (Signal Floating-Yiibai Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-yiibai operation).
SIGILL (Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data.
SIGINT (Signal Interrupt) Interactive attention signal. Generally generated by the application user.
SIGSEGV (Signal Segmentation Violation) Invalid access to storage: When a program tries to read or write outside the memory it is allocated for it.
SIGTERM (Signal Terminate) Termination request sent to program.
  • func -- 這是一個指向函數的指針。這可以是由程序員或一個以下預定義的函數的定義的函數:

SIG_DFL 默認處理:對於某一特定信號,該信號處理的默認操作。
SIG_IGN 忽略信號:信號被忽略。

返回值

這個函數返回前一個信號處理程序或錯誤SIG_ERR的值。

例子

下麵的例子顯示了signal()函數的用法。

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

void sighandler(int);

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

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

   return(0);
}

void sighandler(int signum)
{
   printf("Caught signal %d, coming out...
", signum);
   exit(1);
}

讓我們編譯和運行上麵的程序,這將產生以下結果,程序將無限循環中去。跳出程序使用Ctrl + C鍵。

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...