blob: e7fc33bcadfd6ed72a9a9b0c160751c5ac4585c0 [file] [log] [blame]
William A. Kennington IIIba04ffb2018-09-20 11:35:11 -07001/**
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 <array>
7#include <chrono>
8#include <cstdio>
9#include <sdeventplus/clock.hpp>
10#include <sdeventplus/event.hpp>
11#include <sdeventplus/source/io.hpp>
12#include <sdeventplus/utility/timer.hpp>
13#include <string>
14#include <unistd.h>
15#include <utility>
16
17using sdeventplus::Clock;
18using sdeventplus::ClockId;
19using sdeventplus::Event;
20using sdeventplus::source::IO;
21
22constexpr auto clockId = ClockId::RealTime;
23using Timer = sdeventplus::utility::Timer<clockId>;
24
25int main(int argc, char* argv[])
26{
27 if (argc != 2)
28 {
29 fprintf(stderr, "Usage: %s [seconds]\n", argv[0]);
30 return 1;
31 }
32
33 std::chrono::seconds delay(std::stoul(argv[1]));
34
35 auto event = Event::get_default();
36
37 std::string content;
38 auto timerCb = [&](Timer&) {
39 printf("%s", content.c_str());
40 content.clear();
41 };
42 Timer timer(event, std::move(timerCb));
43
44 auto ioCb = [&](IO&, int fd, uint32_t) {
45 std::array<char, 4096> buffer;
46 ssize_t bytes = read(fd, buffer.data(), buffer.size());
47 if (bytes <= 0)
48 {
49 printf("%s", content.c_str());
50 event.exit(bytes < 0);
51 return;
52 }
53 content.append(buffer.data(), bytes);
54 timer.restartOnce(delay);
55 };
56 IO ioSource(event, STDIN_FILENO, EPOLLIN, std::move(ioCb));
57
58 return event.loop();
59}