summaryrefslogtreecommitdiffstats
path: root/example/delayed_echo.cpp
blob: e7fc33bcadfd6ed72a9a9b0c160751c5ac4585c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * Reads stdin looking for a string, and coalesces that buffer until stdin
 * is calm for the passed in number of seconds.
 */

#include <array>
#include <chrono>
#include <cstdio>
#include <sdeventplus/clock.hpp>
#include <sdeventplus/event.hpp>
#include <sdeventplus/source/io.hpp>
#include <sdeventplus/utility/timer.hpp>
#include <string>
#include <unistd.h>
#include <utility>

using sdeventplus::Clock;
using sdeventplus::ClockId;
using sdeventplus::Event;
using sdeventplus::source::IO;

constexpr auto clockId = ClockId::RealTime;
using Timer = sdeventplus::utility::Timer<clockId>;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s [seconds]\n", argv[0]);
        return 1;
    }

    std::chrono::seconds delay(std::stoul(argv[1]));

    auto event = Event::get_default();

    std::string content;
    auto timerCb = [&](Timer&) {
        printf("%s", content.c_str());
        content.clear();
    };
    Timer timer(event, std::move(timerCb));

    auto ioCb = [&](IO&, int fd, uint32_t) {
        std::array<char, 4096> buffer;
        ssize_t bytes = read(fd, buffer.data(), buffer.size());
        if (bytes <= 0)
        {
            printf("%s", content.c_str());
            event.exit(bytes < 0);
            return;
        }
        content.append(buffer.data(), bytes);
        timer.restartOnce(delay);
    };
    IO ioSource(event, STDIN_FILENO, EPOLLIN, std::move(ioCb));

    return event.loop();
}
OpenPOWER on IntegriCloud