otsdaq-mu2e-stm  5.02.01
signal_handler.hh
1 #ifndef SIGNAL_HANDLER_HH_
2 #define SIGNAL_HANDLER_HH_
3 
4 #include <iostream>
5 #include <csignal>
6 #include <atomic>
7 #include <mutex>
8 #include <thread>
9 #include <condition_variable>
10 #include <chrono>
11 #include <fstream> // File I/O for logging
12 
13 // Stop signal
14 #include "Mu2e-STMDAQ/utils/stop_signal.hh"
15 
16 // Async Logger code
17 #include "Mu2e-STMDAQ/utils/async_logger.hh"
18 
19 // Signal handler class
21 
22 private:
23 
24  // Async Logger
25  const std::shared_ptr<AsyncLogger> logger;
26 
27  // Store reference to CPU utils instance
28  static std::shared_ptr<cpu_utils> cpu;
29 
30  // Flag to request exit confirmation
31  static std::atomic<bool> exit_requested;
32 
33  // Mutex for synchronizing confirmation input
34  static std::mutex confirm_mutex;
35 
36  // Condition variable for confirmation handling
37  static std::condition_variable confirm_cv;
38 
39  // Thread for listening to signals
40  static std::thread signal_thread;
41 
42  // Signal handler function (
43  static void handleSignal(int signal);
44 
45  // Continuously listen for signals and process exit confirmation
46  static void listenForSignals();
47 
48  // Pointer to store the singleton instance
49  static SignalHandler* instance;
50 
51 public:
52 
53  // Constructor
54  explicit SignalHandler(const std::shared_ptr<AsyncLogger>& logger_,
55  const std::shared_ptr<cpu_utils>& cpu_);
56 
57  // Destructor
58  ~SignalHandler() {
59  // Ensure stop flag is set before cleanup
60  stop::trigger_user_stop();
61  // Wait for signal thread to complete execution
62  if (signal_thread.joinable()) signal_thread.join();
63  // Reset static instance pointer
64  instance = nullptr;
65  // Notify user
66  std::cout << "SignalHandler destructor called.\n";
67  }
68 
69 };
70 
71 
72 #endif // SIGNAL_HANDLER_HH_