C signal handling
In the C Standard Library, signal processing defines how a program handles various signals while it executes. A signal can report some exceptional behavior within the program, or a signal can report some asynchronous event outside the program.
Standard signals
The C standard defines only 6 signals. They are all defined in header :SIGABRT– "abort", abnormal termination.SIGFPE– floating point exception.SIGILL– "illegal", invalid instruction.SIGINT– "interrupt", interactive attention request sent to the program.SIGSEGV– "segmentation violation", invalid memory access.SIGTERM– "terminate", termination request sent to the program.
header by the implementation. For example, Unix and Unix-like operating systems define more than 15 additional signals; see Unix signal.Debugging
SIGTRAPfor debugging purposes. It is platform-dependent and may be used on Unix-like operating systems.
Handling
A signal can be generated by callingraise or kill system calls. raise sends a signal to the current process, kill sends a signal to a specific process.A signal handler is a function which is called by the target environment when the corresponding signal occurs. The target environment suspends execution of the program until the signal handler returns or calls
longjmp.Signal handlers can be set with
signal or sigaction. The behavior of signal has been changed multiple times across history and its use is discouraged. It is only portable when used to set a signal's disposition to SIG_DFL or SIG_IGN. Signal handlers can be specified for all but two signals.If the signal reports an error within the program, the signal handler can terminate by calling
abort, exit, or longjmp.Functions
| Function | Description |
| artificially sends a signal to the calling process |
kill | artificially sends a signal to a specified process |
| sets the action taken when the program receives a specific signal |
Example usage
- include
- include
- include
static void catch_function
int main
Other languages
C++
C signals are traditionally used the same way in C++ as in C. However, one can also write wrappers for RAII-style usage.export module org.wikipedia.example;
import
import std;
using std::function;
export namespace org::wikipedia::example
This can also be done with Boost, using the class
boost::asio::signal_set.C#
C signals can be used with P/Invoke andMono.Unix.Native.Syscall.Java
C signals are unofficially usable in Java language, from modulejdk.unsupported, with internal JVM classes sun.misc.Signal and interface sun.misc.SignalHandler.package org.wikipedia.example;
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class Example
Rust
Signals can be used with the signal_hook crate in Rust.use std::process;
use std::thread;
use std::time::Duration;
use signal_hook::consts::signal::*;
use signal_hook::iterator::Signals;
fn main