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 wikipedia.examples; import ; // necessary to obtain macros import std; using std::function; export namespace wikipedia::examples { class Signal { private: using Handler = function; int sig; public: static constexpr int ABRT = SIGABRT; static constexpr int FPE = SIGFPE; static constexpr int ILL = SIGILL; static constexpr int INT = SIGINT; static constexpr int SEGV = SIGSEGV; static constexpr int TERM = SIGTERM; static constexpr int DFL = SIGDFL; static constexpr int IGN = SIGIGN; static constexpr int ERR = SIGERR; explicit Signal(int sig): sig{sig} {}
nodiscard int getSignal() const noexcept { return sig; } Handler handle(Handler handler) const noexcept { return std::signal(sig, handler); } int raise() const noexcept { return std::raise(sig); } }; } This can also be done with
Boost, using the class boost::asio::signal_set.
C# C signals can be used with
P/Invoke and Mono.Unix.Native.Syscall.
Java C signals are unofficially usable in
Java language, from
module jdk.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 { public static void main(String[] args) { SignalHandler handler = new SignalHandler() { public void handle(Signal sig) { boolean handled = handlers.get(type).handle(type); if (!handled) { if (type.getDefaultAction() == SignalType.DefaultAction.IGNORE) { SignalHandler.SIG_IGN.handle(sig); } else { SignalHandler.SIG_DFL.handle(sig); } } } }; Signal.handle(new Signal("INT"), handler); } }
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() { let mut signals: Signals = Signals::new(&[SIGINT, SIGTERM]).expect("Failed to set up signal handling"); thread::spawn(move || { for signal in signals.forever() { match signal { SIGINT => { println!("Received SIGINT (Ctrl+C). Exiting gracefully."); process::exit(0); } SIGTERM => { println!("Received SIGTERM. Exiting gracefully."); process::exit(0); } _ => unreachable!(), } } }); loop { println!("Running..."); thread::sleep(Duration::from_secs(2)); } } ==See also==