信号处理与信号()

信号编号可以是同步的(如 SIGSEGV - 分段故障),当它们由程序本身的故障触发时,或者异步(如 SIGINT-交互式注意),当它们从程序外部启动时,例如通过按键作为 Cntrl-C

signal() 功能是 ISO C 标准的一部分,可用于分配处理特定信号的功能

#include <stdio.h>  /* printf() */
#include <stdlib.h> /* abort()  */
#include <signal.h> /* signal() */

void handler_nonportable(int sig)
{
    /* undefined behavior, maybe fine on specific platform */
    printf("Catched: %d\n", sig);
    
    /* abort is safe to call */
    abort();
}

sig_atomic_t volatile finished = 0;

void handler(int sig)
{
    switch (sig) {
    /* hardware interrupts should not return */
    case SIGSEGV:
    case SIGFPE:
    case SIGILL:

Version >= C11

      /* quick_exit is safe to call */
      quick_exit(EXIT_FAILURE);

Version < C11

      /* use _Exit in pre-C11 */
      _Exit(EXIT_FAILURE);
    default:
       /* Reset the signal to the default handler, 
          so we will not be called again if things go
          wrong on return. */
      signal(sig, SIG_DFL);
      /* let everybody know that we are finished */
      finished = sig;
      return;
   }
}

int main(void)
{

    /* Catch the SIGSEGV signal, raised on segmentation faults (i.e NULL ptr access */
    if (signal(SIGSEGV, &handler) == SIG_ERR) {
        perror("could not establish handler for SIGSEGV");
        return EXIT_FAILURE;
    }

    /* Catch the SIGTERM signal, termination request */
    if (signal(SIGTERM, &handler) == SIG_ERR) {
        perror("could not establish handler for SIGTERM");
        return EXIT_FAILURE;
    }

    /* Ignore the SIGINT signal, by setting the handler to `SIG_IGN`. */
    signal(SIGINT, SIG_IGN);

    /* Do something that takes some time here, and leaves
       the time to terminate the program from the keyboard. */

    /* Then: */

    if (finished) {
       fprintf(stderr, "we have been terminated by signal %d\n", (int)finished);
        return EXIT_FAILURE;
    }

    /* Try to force a segmentation fault, and raise a SIGSEGV */
    {
      char* ptr = 0;
      *ptr = 0;
    }

    /* This should never be executed */
    return EXIT_SUCCESS;
}

使用 signal() 会对信号处理程序中允许的内容施加重要限制,请参阅备注以获取更多信息。

POSIX 建议使用 sigaction() 而不是 signal(),因为它具有不明确的行为和重要的实现变化。POSIX 还定义比 ISO C 标准更多的信号 ,包括 SIGUSR1SIGUSR2,它们可以由程序员自由地用于任何目的。