blob: 1b700d06acc51e29dc486873eebda77bed16275b [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
Patrick Williamsa8c11e32023-05-10 07:50:56 -05006#include <unistd.h>
7
William A. Kennington IIIba04ffb2018-09-20 11:35:11 -07008#include <sdeventplus/clock.hpp>
9#include <sdeventplus/event.hpp>
10#include <sdeventplus/source/io.hpp>
11#include <sdeventplus/utility/timer.hpp>
Patrick Williamsa8c11e32023-05-10 07:50:56 -050012
13#include <array>
14#include <chrono>
15#include <cstdio>
William A. Kennington IIIba04ffb2018-09-20 11:35:11 -070016#include <string>
William A. Kennington IIIba04ffb2018-09-20 11:35:11 -070017#include <utility>
18
19using sdeventplus::Clock;
20using sdeventplus::ClockId;
21using sdeventplus::Event;
22using sdeventplus::source::IO;
23
24constexpr auto clockId = ClockId::RealTime;
25using Timer = sdeventplus::utility::Timer<clockId>;
26
27int 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;
William A. Kennington III7cc1ec92021-10-25 01:55:00 -070048 ssize_t bytes = read(fd, buffer.data(), 4096);
William A. Kennington IIIba04ffb2018-09-20 11:35:11 -070049 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}