Turi Create  4.0
console_cancel_handler.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef CPPIPC_SERVER_CONSOLE_CANCEL_HANDLER_HPP
7 #define CPPIPC_SERVER_CONSOLE_CANCEL_HANDLER_HPP
8 #include <atomic>
9 #include <iostream>
10 #include <core/export.hpp>
11 /**
12  * \ingroup cppipc
13  *
14  * Singleton object that sets the system-specific handler of a
15  * "cancel" event from a console application. This could be Ctrl+C (UNIX and
16  * Windows), Ctrl+Break (just Windows), and whatever some other system
17  * supports. This abstraction handles ONLY cancel events and no other signals,
18  * as it is much more difficult to provide a cross-platform signal handling
19  * method.
20  */
21 
22 namespace cppipc {
23 
24 class EXPORT console_cancel_handler {
25  public:
26  static console_cancel_handler& get_instance();
27 
28  // Guarantees that if this returns false, new handler wasn't set
29  // TODO: Check that statement
30  // TODO: Get this to take an arbitrary function
31  virtual bool set_handler() { return false; }
32 
33  // If this fails, your signal handler could be in a weird state...m_sigint_act
34  // will be set still. Sorry!
35  virtual bool unset_handler() { return false; }
36 
37  virtual void raise_cancel() {}
38 
39  bool get_cancel_flag() {
40  return m_cancel_on.load();
41  }
42 
43  void set_cancel_flag(bool val) {
44  m_cancel_on.store(val);
45  }
46 
47  protected:
48  console_cancel_handler() {
49  this->set_cancel_flag(false);
50  }
51 
52  std::atomic<bool> m_cancel_on;
53 
54  bool m_handler_installed = false;
55 
56  private:
57  console_cancel_handler(console_cancel_handler const&) = delete;
58 
59  console_cancel_handler& operator=(console_cancel_handler const&) = delete;
60 
61 };
62 
63 } // namespace cppipc
64 
65 #endif //CPPIPC_SERVER_CONSOLE_CANCEL_HANDLER_HPP