gondola_core/tof/
signal_handler.rs

1// This file is part of gaps-online-software and published 
2// under the GPLv3 license
3
4use std::thread;
5use std::sync::{
6  Arc,
7  Mutex
8};
9use colored::{
10    Colorize,
11    //ColoredString
12};
13
14use signal_hook::iterator::Signals;
15use signal_hook::consts::signal::{
16  SIGTERM,
17  SIGINT
18};
19use std::os::raw::c_int;
20use std::time::Duration;
21use crate::tof::ThreadControl;
22
23
24/// Handle incoming POSIX signals and inform threads about 
25/// the state.
26///
27/// Allows to terminate multithreaded application safevly 
28/// when CTRL+C is pressed
29pub fn signal_handler(thread_control     : Arc<Mutex<ThreadControl>>) {
30  let sleep_time = Duration::from_millis(300);
31  let mut signals = Signals::new(&[SIGTERM, SIGINT]).expect("Unknown signals");
32  'main: loop {
33    thread::sleep(sleep_time);
34
35    // check pending signals and handle
36    // SIGTERM and SIGINT
37    for signal in signals.pending() {
38      match signal as c_int {
39        SIGTERM | SIGINT => {
40          println!("=> {}", String::from("SIGTERM or SIGINT received. Maybe Ctrl+C has been pressed! Commencing program shutdown!").red().bold());
41          match thread_control.lock() {
42            Ok(mut tc) => {
43              tc.sigint_recvd = true;
44            }
45            Err(err) => {
46              error!("Can't acquire lock for ThreadControl! {err}");
47            },
48          }
49          break 'main; // now end myself
50        } 
51        _ => {
52          error!("Received signal, but I don't have instructions what to do about it!");
53        }
54      }
55    }
56  }
57}