cepgen is hosted by Hepforge, IPPP Durham
CepGen N/A
Central exclusive processes event generator
AbortHandler.h
Go to the documentation of this file.
1/*
2 * CepGen: a central exclusive processes event generator
3 * Copyright (C) 2017-2024 Laurent Forthomme
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19#ifndef CepGen_Utils_AbortHandler_h
20#define CepGen_Utils_AbortHandler_h
21
22#include <atomic>
23#include <csignal>
24
26
27namespace cepgen::utils {
28 extern std::atomic<int> gSignal;
30 struct RunAbortedException : std::runtime_error {
31 RunAbortedException() : std::runtime_error("CepGen run aborted") {}
32 ~RunAbortedException() noexcept override { CG_INFO("RunAbortedException") << "Run aborted by user interaction."; }
33
34 const char* what() const noexcept override { return "User abort through C-c."; }
35 };
36
39 public:
41 explicit AbortHandler(int flags = SA_SIGINFO) {
42 action_.sa_sigaction = handle_ctrl_c;
43 sigemptyset(&action_.sa_mask);
44 action_.sa_flags = flags;
45 init();
46 }
47
48 private:
49 static void handle_ctrl_c(int signal, siginfo_t* si, void*) {
50 gSignal = signal;
51 if (abs(si->si_code) != SIGABRT)
52 throw RunAbortedException();
53 }
54 void init() const {
55 if (sigaction(SIGINT, &action_, nullptr) != 0 || sigaction(SIGTERM, &action_, nullptr) != 0)
56 throw CG_FATAL("AbortHandler") << "Failed to initialise the C-c handler!";
57 }
58 struct sigaction action_;
59 };
60} // namespace cepgen::utils
61
62#endif
#define CG_FATAL(mod)
Definition Exception.h:60
#define CG_INFO(mod)
Definition Message.h:200
Object handling a user-driven process abortion.
AbortHandler(int flags=SA_SIGINFO)
Define a process abortion procedure.
Collection of utilities.
std::atomic< int > gSignal
Exception raised when the user terminates the process.
~RunAbortedException() noexcept override
const char * what() const noexcept override