algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
signal_stop.hpp
1#pragma once
2
3#include "./stop.hpp"
4
5#include <atomic>
6#include <csignal>
7
8namespace algotradelib {
9namespace runner {
10
31public:
40 static void install(StopSource& source) noexcept {
41 slot().store(&source, std::memory_order_release);
42 std::signal(SIGINT, &SignalStop::handle);
43 std::signal(SIGTERM, &SignalStop::handle);
44#ifdef SIGHUP
45 // Ignored: SIGHUP's default disposition would terminate the process.
46 std::signal(SIGHUP, SIG_IGN);
47#endif
48 }
49
51 static void uninstall() noexcept {
52 std::signal(SIGINT, SIG_DFL);
53 std::signal(SIGTERM, SIG_DFL);
54#ifdef SIGHUP
55 std::signal(SIGHUP, SIG_DFL);
56#endif
57 slot().store(nullptr, std::memory_order_release);
58 }
59
64 static StopSource* installed() noexcept { return slot().load(std::memory_order_acquire); }
65
66private:
67 // The handler, which does exactly one thing.
68 //
69 // Everything async-signal-unsafe is absent by construction: no allocation, no locking, no I/O, no
70 // `errno` use. It loads a pointer from a lock-free atomic and calls `StopSource::request`, which
71 // is itself nothing but a compare-exchange on a lock-free atomic.
72 static void handle(int) noexcept {
73 if (StopSource* source = slot().load(std::memory_order_acquire)) {
74 source->request(StopIntent::QUIESCE);
75 }
76 }
77
78 // Where the handler finds its destination.
79 //
80 // Atomic because a handler can run on any thread at any time relative to `install`, and a
81 // plain pointer read would be a data race. Function-local static inside an inline accessor keeps
82 // this header-only with exactly one instance across translation units.
83 static std::atomic<StopSource*>& slot() noexcept {
84 static std::atomic<StopSource*> value{nullptr};
85 return value;
86 }
87};
88
89} // namespace runner
90} // namespace algotradelib
Routes SIGINT and SIGTERM to a StopSource as a quiesce, and ignores SIGHUP where it exists (POSIX); o...
static StopSource * installed() noexcept
Returns the installed source.
static void install(StopSource &source) noexcept
Installs the handlers: SIGINT and SIGTERM request a quiesce on source; SIGHUP, where it exists,...
static void uninstall() noexcept
Restores the default disposition of SIGINT, SIGTERM and (POSIX) SIGHUP, and forgets the source.
A stop request the loop polls; safe to set from a signal handler.
Definition stop.hpp:158
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
@ QUIESCE
Stop sending new orders; nothing is cancelled or closed. The default, and what a signal means.
Definition stop.hpp:34
The library: broker-neutral types (core), and the modules below.