C Standard Library -<signal.h>

Introduction

<signal.h>It is a header file in the C standard library used for handling signals.

signal.hThe header file defines a variable typesig_atomic_ttwo function calls, and some macros to handle different signals reported during program execution.

A signal is an asynchronous notification mechanism that allows a process to execute a predefined handler function when a specific event occurs.

Below is a simple example program demonstrating how to use the signal function to catch the SIGINT signal (usually generated by Ctrl+C).

Example

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

// Global variable indicating whether the program should exit
volatile sig_atomic_t stop = 0;

void handle_sigint(int sig) {
    printf("Caught signal %d\n", sig);
    stop = 1; // Set the exit flag
}

int main() {
    // Set the handler for the SIGINT signal to the handle_sigint function
    signal(SIGINT, handle_sigint);

    while (!stop) { // Check whether to exit
        printf("Running...\n");
        sleep(1);
    }

    printf("Exiting...\n");

    return 0;
}

In the above code, when the program is running, if the user pressesCtrl+C, it will catch the SIGINT signal and call the handle_sigint function, printing the signal number.

Compile and execute the above code, the output is as follows:

Running...
Running...
Running...
^CCaught signal 2
Exiting...

Code Analysis:

  • volatile sig_atomic_t stop = 0;: define a global variablestop, used to indicate whether the program should exit. Usingvolatilethe keyword ensures that the compiler will not optimize away accesses to this variable, because it may be modified in a signal handler.sig_atomic_tThe type guarantees that accesses to this variable are atomic.
  • Inhandle_sigintIn the signal handler function, setstopto 1, indicating the program should exit.
  • In the main loop, checkstopthe value of the variable; if it is set to 1, break out of the loop and end the program.

Library variables

The following are variable types defined in the header file signal.h:

Serial NumberVariables & Description
1sig_atomic_t
This isintType, used as a variable in signal handlers. It is an integer type of an object that can be accessed as an atomic entity even in the presence of asynchronous signals.
2sigset_t
A data type used to represent a signal set.

Library macros

<

In the C standard library,SIG_Prefix macros andsignalUsed together with functions to define and handle signal behavior. The following are commonSIG_Macros and their uses:

Serial NumberMacros & Description
1 SIG_DFL
Represents the default handler for a signal. Use this macro to restore a signal to its default behavior.
2 SIG_ERR
Represents the return value when an error occurs in setting a signal handler function.
3 SIG_IGN
Ignore signal.

Signal types:

ConstantsDescription
SIGABRTbyabortThe signal generated by the function, indicating abnormal termination
SIGALRMbyalarmThe timer expiration signal set by the function
SIGBUSIllegal memory access (for example, accessing an unaligned memory address)
SIGCHLDChild process status changed (exited or stopped)
SIGCONTContinue executing a suspended process
SIGFPEArithmetic errors (for example, division by zero, floating-point exceptions)
SIGHUPHangup signal (usually used to detect terminal disconnect)
SIGILLIllegal instruction
SIGINTInterrupt signal (usually generated by Ctrl+C)
SIGKILLImmediate termination signal (cannot be caught or ignored)
SIGPIPEWrite data to a pipe with no read process
SIGQUITTerminal quit signal (usually generated by Ctrl+\), produces a core dump
SIGSEGVSegmentation fault (illegal memory access)
SIGSTOPStops process execution (cannot be caught or ignored)
SIGTERMTermination signal
SIGTSTPSuspends the process (usually generated by Ctrl+Z)
SIGTTINSignal generated when a background process reads data from the terminal
SIGTTOUSignal generated when a background process writes data to the terminal
SIGUSR1User-defined signal 1
SIGUSR2User-defined signal 2
SIGPOLLI/O event (replaces SIGIO)
SIGPROFTimer expiration signal (bysetitimerthe set profiling timer)
SIGSYSIllegal system call
SIGTRAPBreakpoint or trap instruction
SIGURGSocket urgent condition signal
SIGVTALRMVirtual clock timer expiration signal
SIGXCPUExceeded CPU time limit
SIGXFSZExceeded file size limit

Library functions

The following are functions defined in the header file signal.h:

Function Description
void (*signal(int sig, void (*func)(int)))(int); Set the signal handler.
int raise(int sig); Send a signal to the current process.
int kill(pid_t pid, int sig); Send a signal to the specified process.
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Check or change the blocked signal set.
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact); Check or change the signal handler.
int sigsuspend(const sigset_t *mask); Temporarily replace the current signal mask and suspend the process until a signal is caught.
int sigpending(sigset_t *set); Check the pending signal set.
int sigemptyset(sigset_t *set); Initialize the signal set to an empty set.
int sigfillset(sigset_t *set); Initialize the signal set to the full signal set.
int sigaddset(sigset_t *set, int signum); Add the specified signal to the signal set.
int sigdelset(sigset_t *set, int signum); Remove the specified signal from the signal set.
int sigismember(const sigset_t *set, int signum); Check whether the specified signal is in the signal set.
void abort(void); raiseSIGABRTThe signal causes abnormal termination of the process.
unsigned int alarm(unsigned int seconds); After the specified number of seconds, sendSIGALRMsignal to the calling process.
int pause(void); Suspend the process until a signal is caught.
void psignal(int sig, const char *s); Print signal description information.
char *strsignal(int sig); Return the signal description string.
int sigwait(const sigset_t *set, int *sig); Block waiting for a signal and handle it.
other extensions