posix_signal_blocker.hpp 2.0 KB

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