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