1 /**
2 * Reads stdin looking for a string, and coalesces that buffer until stdin
3 * is calm for the passed in number of seconds.
4 */
5
6 #include <unistd.h>
7
8 #include <sdeventplus/clock.hpp>
9 #include <sdeventplus/event.hpp>
10 #include <sdeventplus/source/io.hpp>
11 #include <sdeventplus/utility/timer.hpp>
12
13 #include <array>
14 #include <chrono>
15 #include <cstdio>
16 #include <string>
17 #include <utility>
18
19 using sdeventplus::Clock;
20 using sdeventplus::ClockId;
21 using sdeventplus::Event;
22 using sdeventplus::source::IO;
23
24 constexpr auto clockId = ClockId::RealTime;
25 using Timer = sdeventplus::utility::Timer<clockId>;
26
main(int argc,char * argv[])27 int main(int argc, char* argv[])
28 {
29 if (argc != 2)
30 {
31 fprintf(stderr, "Usage: %s [seconds]\n", argv[0]);
32 return 1;
33 }
34
35 std::chrono::seconds delay(std::stoul(argv[1]));
36
37 auto event = Event::get_default();
38
39 std::string content;
40 auto timerCb = [&](Timer&) {
41 printf("%s", content.c_str());
42 content.clear();
43 };
44 Timer timer(event, std::move(timerCb));
45
46 auto ioCb = [&](IO&, int fd, uint32_t) {
47 std::array<char, 4096> buffer;
48 ssize_t bytes = read(fd, buffer.data(), 4096);
49 if (bytes <= 0)
50 {
51 printf("%s", content.c_str());
52 event.exit(bytes < 0);
53 return;
54 }
55 content.append(buffer.data(), bytes);
56 timer.restartOnce(delay);
57 };
58 IO ioSource(event, STDIN_FILENO, EPOLLIN, std::move(ioCb));
59
60 return event.loop();
61 }
62