Ticket #2879: sigselect.cpp

File sigselect.cpp, 2.0 KB (added by dgoncharov@…, 14 years ago)

an example

Line 
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 <sys/select.h>
7#include <signal.h>
8
9#include <cstdio>
10#include <cstdlib>
11#include <cerrno>
12#include <cstring>
13
14#include <iostream>
15#include <iomanip>
16#include <string>
17
18#include <boost/asio/posix/signalfd.hpp>
19
20using std::cout;
21using std::cin;
22using std::endl;
23using std::cerr;
24using std::flush;
25
26namespace bap = boost::asio::posix;
27
28int main(int argc, char const* argv[])
29{
30 bap::signalfd<SIGINT> sigint;
31 int const intfd = sigint.fd();
32
33 bap::signalfd<SIGTERM> sigterm;
34 int const termfd = sigterm.fd();
35
36 cout << "Type to watch stdin activity. Send signals to watch the program react. Use ^D to exit" << endl << "# " << flush;
37 while (std::cin)
38 {
39 fd_set rfds;
40 FD_ZERO(&rfds);
41 FD_SET(STDIN_FILENO, &rfds);
42 FD_SET(intfd, &rfds);
43 FD_SET(termfd, &rfds);
44
45 int const s = select(std::max(intfd, termfd) + 1, &rfds, 0, 0, 0);
46 if (s < 0)
47 {
48 if (EINTR != errno)
49 cerr << "select(): " << strerror(errno) << endl;
50 continue;
51 }
52 if (FD_ISSET(0, &rfds))
53 {
54 std::string s;
55 std::getline(cin, s);
56 cout << "activity on stdin: " << s << endl;
57 }
58 else if (FD_ISSET(intfd, &rfds))
59 {
60 cout << "sigint received" << endl;
61 char c;
62 int const s = read(intfd, &c, sizeof c);
63 if (s < 0)
64 cerr << "Cannot read from intfd: read(): " << strerror(errno) << endl;
65 }
66 else if (FD_ISSET(termfd, &rfds))
67 {
68 cout << "sigterm received" << endl;
69 char c;
70 int const s = read(termfd, &c, sizeof c);
71 if (s < 0)
72 cerr << "Cannot read from termfd: read(): " << strerror(errno) << endl;
73 }
74 cout << "# " << flush;
75 }
76 cout << "\nstdin closed. Bye" << endl;
77}
78