posix_signal_blocker.hpp 1.9 KB

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