I have the following program that just runs a timer for 5 seconds and has a signal handler.
#include <boost/asio.hpp>
#include <chrono>
#include <iostream>
#include <signal.h>
boost::asio::io_context io;
void signal_handler(
const boost::system::error_code& ec,
int signal_number)
{
std::cout << "Received signal " << signal_number << " [" << ec << "]" << std::endl;
}
boost::asio::awaitable<void> session()
{
try {
boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));
boost::system::error_code ec;
t.wait(ec); // 1
// co_await t.async_wait(boost::asio::redirect_error(boost::asio::use_awaitable, ec)); // 2
std::cout << "Socket connect timed out [" << ec << "]" << std::endl;
}
catch (...) {
std::cout << "Exception" << std::endl;
}
co_return;
}
int main(int argc, char *argv[]) {
boost::asio::signal_set signals(io, SIGINT);
signals.async_wait(signal_handler);
boost::asio::co_spawn(io, session(), boost::asio::detached);
io.run();
}
When I generate SIGINT the program exits immediately with the following log:
^CSocket connect timed out [system:4]
Received signal 2 [system:0]
The initial version uses synchronous timer and uses it by calling wait methond. When I comment line // 1 and uncomment line // 2 and generate SIGINT programs exits after 5 seconds with the following log:
^CReceived signal 2 [system:0]
Socket connect timed out [system:0]
Second version uses async_wait method and coroutine approach to trigger the 5 seconds wait.
I would like to understand why there is a difference in behavior, what is happening under the hood and which one is more natural to the asio library.