| 1 | // Copyright (c) 2009 Dmitry Goncharov
|
|---|
| 2 | //
|
|---|
| 3 | // Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|---|
| 4 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|---|
| 5 |
|
|---|
| 6 | #include <iostream>
|
|---|
| 7 | #include <iomanip>
|
|---|
| 8 | #include <string>
|
|---|
| 9 | #include <boost/bind.hpp>
|
|---|
| 10 | #include <boost/system/system_error.hpp>
|
|---|
| 11 | #include <boost/asio/io_service.hpp>
|
|---|
| 12 | #include <boost/asio/posix/stream_descriptor.hpp>
|
|---|
| 13 | #include <boost/asio/posix/signal_handler.hpp>
|
|---|
| 14 |
|
|---|
| 15 | using std::cout;
|
|---|
| 16 | using std::cin;
|
|---|
| 17 | using std::endl;
|
|---|
| 18 | using std::cerr;
|
|---|
| 19 | using std::flush;
|
|---|
| 20 |
|
|---|
| 21 | namespace ba = boost::asio;
|
|---|
| 22 | namespace bap = boost::asio::posix;
|
|---|
| 23 |
|
|---|
| 24 | void on_signal(boost::system::error_code const& error, int signo)
|
|---|
| 25 | {
|
|---|
| 26 | if (!error)
|
|---|
| 27 | cout << "signal #" << signo << " received" << endl << "# " << flush;
|
|---|
| 28 | }
|
|---|
| 29 |
|
|---|
| 30 | void on_stdin(boost::system::error_code const& error, char const* buf, std::size_t buflen, int* running)
|
|---|
| 31 | {
|
|---|
| 32 | if (!error)
|
|---|
| 33 | {
|
|---|
| 34 | assert(buflen >= 1 && "Incorrect usage of boost::asio");
|
|---|
| 35 | cout << "activity on stdin: " << std::string(buf, buflen - 1) << endl << "# " << flush;
|
|---|
| 36 | }
|
|---|
| 37 | else
|
|---|
| 38 | {
|
|---|
| 39 | cout << "stdin error: " << error << endl;
|
|---|
| 40 | if (ba::error::eof == error)
|
|---|
| 41 | {
|
|---|
| 42 | cout << "stdin closed." << flush;
|
|---|
| 43 | *running = 0;
|
|---|
| 44 | }
|
|---|
| 45 | }
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | int main(int argc, char const* argv[])
|
|---|
| 49 | {
|
|---|
| 50 | ba::io_service ios;
|
|---|
| 51 |
|
|---|
| 52 | bap::signal_handler<SIGINT> sigint(ios);
|
|---|
| 53 | bap::signal_handler<SIGTERM> sigterm(ios);
|
|---|
| 54 |
|
|---|
| 55 | bap::stream_descriptor std_in(ios, STDIN_FILENO);
|
|---|
| 56 |
|
|---|
| 57 | cout << "Type to watch stdin activity. Send signals to watch the program react. Use ^D to exit" << endl << "# " << flush;
|
|---|
| 58 |
|
|---|
| 59 | int running = 1;
|
|---|
| 60 | while (running)
|
|---|
| 61 | {
|
|---|
| 62 | ios.reset();
|
|---|
| 63 |
|
|---|
| 64 | sigint.async_wait(boost::bind(on_signal, _1, SIGINT));
|
|---|
| 65 | sigterm.async_wait(boost::bind(on_signal, _1, SIGTERM));
|
|---|
| 66 |
|
|---|
| 67 | char buf[1024];
|
|---|
| 68 | std_in.async_read_some(ba::buffer(buf, sizeof buf), boost::bind(on_stdin, _1, buf, _2, &running));
|
|---|
| 69 |
|
|---|
| 70 | ios.poll();
|
|---|
| 71 | }
|
|---|
| 72 | cout << " Bye" << endl;
|
|---|
| 73 | }
|
|---|
| 74 |
|
|---|
| 75 |
|
|---|