• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // detail/posix_signal_blocker.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10 
11 #ifndef ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
12 #define ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
13 
14 
15 #include "asio/detail/config.hpp"
16 
17 #if defined(ASIO_HAS_PTHREADS)
18 
19 #include <csignal>
20 #include <pthread.h>
21 #include <signal.h>
22 #include "asio/detail/noncopyable.hpp"
23 
24 #include "asio/detail/push_options.hpp"
25 
26 namespace asio {
27 namespace detail {
28 
29 class posix_signal_blocker
30   : private noncopyable
31 {
32 public:
33   // Constructor blocks all signals for the calling thread.
posix_signal_blocker()34   posix_signal_blocker()
35     : blocked_(false)
36   {
37     sigset_t new_mask;
38     sigfillset(&new_mask);
39     blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0);
40   }
41 
42   // Destructor restores the previous signal mask.
~posix_signal_blocker()43   ~posix_signal_blocker()
44   {
45     if (blocked_)
46       pthread_sigmask(SIG_SETMASK, &old_mask_, 0);
47   }
48 
49   // Block all signals for the calling thread.
block()50   void block()
51   {
52     if (!blocked_)
53     {
54       sigset_t new_mask;
55       sigfillset(&new_mask);
56       blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0);
57     }
58   }
59 
60   // Restore the previous signal mask.
unblock()61   void unblock()
62   {
63     if (blocked_)
64       blocked_ = (pthread_sigmask(SIG_SETMASK, &old_mask_, 0) != 0);
65   }
66 
67 private:
68   // Have signals been blocked.
69   bool blocked_;
70 
71   // The previous signal mask.
72   sigset_t old_mask_;
73 };
74 
75 } // namespace detail
76 } // namespace asio
77 
78 #include "asio/detail/pop_options.hpp"
79 
80 #endif // defined(ASIO_HAS_PTHREADS)
81 
82 #endif // ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
83