aboutsummaryrefslogtreecommitdiff
path: root/ttwhy/main.cpp
blob: c210bee4d951038fa3807a6c3f2550f1ec10bfe6 (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
#include <asio.hpp>
#include <stdio.h>

import ttwhy;

auto handle_signals(asio::cancellation_signal & cancellation_signal) -> asio::awaitable<void>
{
  co_await asio::this_coro::reset_cancellation_state(asio::disable_cancellation());
  co_await asio::this_coro::throw_if_cancelled(false);

  auto executor = co_await asio::this_coro::executor;
  auto signals = asio::signal_set{executor, SIGINT, SIGTERM};
  auto log_stream = asio::posix::stream_descriptor{executor, fileno(stdout)};

  auto [error, signal] = co_await signals.async_wait(asio::as_tuple(asio::use_awaitable));

  if (!error)
  {
    co_await asio::async_write(log_stream, asio::buffer("shutting down...\n"), asio::as_tuple(asio::use_awaitable));
    cancellation_signal.emit(asio::cancellation_type::all);
  }
}

auto main() -> int
{
  auto terminal_attributes = ttwhy::scoped_attributes{fileno(stdin)}  //
                                 .canonical_mode(false)
                                 .echo(false);
  auto context = asio::io_context{};
  auto cancellation_signal = asio::cancellation_signal{};

  asio::co_spawn(context, handle_signals(cancellation_signal), asio::detached);

  context.run();
}