posix_signal_blocker.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // posix_signal_blocker.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2008 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. #ifndef BOOST_ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
  11. #define BOOST_ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/push_options.hpp>
  16. #include <boost/asio/detail/push_options.hpp>
  17. #include <boost/config.hpp>
  18. #include <boost/asio/detail/pop_options.hpp>
  19. #if defined(BOOST_HAS_PTHREADS)
  20. #include <boost/asio/detail/push_options.hpp>
  21. #include <csignal>
  22. #include <pthread.h>
  23. #include <signal.h>
  24. #include <boost/asio/detail/pop_options.hpp>
  25. #include <boost/asio/detail/noncopyable.hpp>
  26. namespace boost {
  27. namespace asio {
  28. namespace detail {
  29. class posix_signal_blocker
  30. : private noncopyable
  31. {
  32. public:
  33. // Constructor blocks all signals for the calling thread.
  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. // Destructor restores the previous signal mask.
  42. ~posix_signal_blocker()
  43. {
  44. if (blocked_)
  45. pthread_sigmask(SIG_SETMASK, &old_mask_, 0);
  46. }
  47. // Block all signals for the calling thread.
  48. void block()
  49. {
  50. if (!blocked_)
  51. {
  52. sigset_t new_mask;
  53. sigfillset(&new_mask);
  54. blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0);
  55. }
  56. }
  57. // Restore the previous signal mask.
  58. void unblock()
  59. {
  60. if (blocked_)
  61. blocked_ = (pthread_sigmask(SIG_SETMASK, &old_mask_, 0) != 0);
  62. }
  63. private:
  64. // Have signals been blocked.
  65. bool blocked_;
  66. // The previous signal mask.
  67. sigset_t old_mask_;
  68. };
  69. } // namespace detail
  70. } // namespace asio
  71. } // namespace boost
  72. #endif // defined(BOOST_HAS_PTHREADS)
  73. #include <boost/asio/detail/pop_options.hpp>
  74. #endif // BOOST_ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP