2 // pipe_select_interrupter.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
11 #ifndef BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP
12 #define BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/push_options.hpp>
20 #include <boost/asio/detail/push_options.hpp>
21 #include <boost/config.hpp>
22 #include <boost/throw_exception.hpp>
23 #include <boost/system/system_error.hpp>
24 #include <boost/asio/detail/pop_options.hpp>
26 #if !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
28 #include <boost/asio/detail/push_options.hpp>
30 #include <boost/asio/detail/pop_options.hpp>
32 #include <boost/asio/error.hpp>
33 #include <boost/asio/detail/socket_types.hpp>
39 class pipe_select_interrupter
43 pipe_select_interrupter()
46 if (pipe(pipe_fds
) == 0)
48 read_descriptor_
= pipe_fds
[0];
49 ::fcntl(read_descriptor_
, F_SETFL
, O_NONBLOCK
);
50 write_descriptor_
= pipe_fds
[1];
51 ::fcntl(write_descriptor_
, F_SETFL
, O_NONBLOCK
);
55 boost::system::error_code
ec(errno
,
56 boost::asio::error::get_system_category());
57 boost::system::system_error
e(ec
, "pipe_select_interrupter");
58 boost::throw_exception(e
);
63 ~pipe_select_interrupter()
65 if (read_descriptor_
!= -1)
66 ::close(read_descriptor_
);
67 if (write_descriptor_
!= -1)
68 ::close(write_descriptor_
);
71 // Interrupt the select call.
75 int result
= ::write(write_descriptor_
, &byte
, 1);
79 // Reset the select interrupt. Returns true if the call was interrupted.
83 int bytes_read
= ::read(read_descriptor_
, data
, sizeof(data
));
84 bool was_interrupted
= (bytes_read
> 0);
85 while (bytes_read
== sizeof(data
))
86 bytes_read
= ::read(read_descriptor_
, data
, sizeof(data
));
87 return was_interrupted
;
90 // Get the read descriptor to be passed to select.
91 int read_descriptor() const
93 return read_descriptor_
;
97 // The read end of a connection used to interrupt the select call. This file
98 // descriptor is passed to select such that when it is time to stop, a single
99 // byte will be written on the other end of the connection and this
100 // descriptor will become readable.
101 int read_descriptor_
;
103 // The write end of a connection used to interrupt the select call. A single
104 // byte may be written to this to wake up the select which is waiting for the
105 // other end to become readable.
106 int write_descriptor_
;
109 } // namespace detail
113 #endif // !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
115 #include <boost/asio/detail/pop_options.hpp>
117 #endif // BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP