c++ - SO_RCVTIME和SO_RCVTIMEO不影响Boost.Asio操作

标签 c++ linux boost boost-asio

下面是我的代码

boost::asio::io_service io;
boost::asio::ip::tcp::acceptor::reuse_address option(true);
boost::asio::ip::tcp::acceptor accept(io);
boost::asio::ip::tcp::resolver resolver(io);
boost::asio::ip::tcp::resolver::query query("0.0.0.0", "8080");
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
accept.open(endpoint.protocol());
accept.set_option(option);
accept.bind(endpoint);
accept.listen(30);

boost::asio::ip::tcp::socket ps(io);

accept.accept(ps);

struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
//setsockopt(ps.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
setsockopt(ps.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
char buf[1024];
ps.async_receive(boost::asio::buffer(buf, 1024), boost::bind(fun));
io.run();

当我使用Telnet连接但不发送数据时,它不会与Telnet超时断开连接。是否需要做些setockopt踢进来?
谢谢!

我已经将SO_RCVTIMEO修改为SO_SNDTIMEO。在指定的时间内仍无法超时

最佳答案

在Boost.Asio中使用SO_RCVTIMEOSO_SNDTIMEO套接字选项很少会产生所需的行为。考虑使用以下两种模式之一:

使用async_wait()进行组合操作

可以通过使用Boost.Asio计时器和带有async_wait()操作的async_receive()操作来构成具有超时的异步读取操作。 Boost.Asio timeout examples演示了这种方法,类似于:

// Start a timeout for the read.
boost::asio::deadline_timer timer(io_service);
timer.expires_from_now(boost::posix_time::seconds(1));
timer.async_wait(
  [&socket, &timer](const boost::system::error_code& error)
  {
    // On error, such as cancellation, return early.
    if (error) return;

    // Timer has expired, but the read operation's completion handler
    // may have already ran, setting expiration to be in the future.
    if (timer.expires_at() > boost::asio::deadline_timer::traits_type::now())
    {
      return;
    } 

    // The read operation's completion handler has not ran.
    boost::system::error_code ignored_ec;
    socket.close(ignored_ec);
  });

// Start the read operation.
socket.async_receive(buffer,
  [&socket, &timer](const boost::system::error_code& error,
    std::size_t bytes_transferred)
  {
    // Update timeout state to indicate the handler has ran.  This
    // will cancel any pending timeouts.
    timer.expires_at(boost::posix_time::pos_infin);

    // On error, such as cancellation, return early.
    if (error) return;

    // At this point, the read was successful and buffer is populated.
    // However, if the timeout occurred and its completion handler ran first,
    // then the socket is closed (!socket.is_open()).
  });

请注意,两个异步操作都可能在同一迭代中完成,这使得两个完成处理程序都可以成功运行。因此,这是两个完成处理程序都需要更新和检查状态的原因。有关如何管理状态的更多详细信息,请参见this答案。

使用std::future
Boost.Asio提供support for C++11 futures。当将 boost::asio::use_future 作为异步操作的完成处理程序提供时,初始化函数将返回一个std::future,该代码将在操作完成后得到满足。由于std::future支持定时等待,因此可以利用它来使操作超时。请注意,由于调用线程将被阻塞以等待将来,因此至少另一个线程必须正在处理io_service,以允许async_receive()操作进行并实现 promise :

// Use an asynchronous operation so that it can be cancelled on timeout.
std::future<std::size_t> read_result = socket.async_receive(
   buffer, boost::asio::use_future);

// If timeout occurs, then cancel the read operation.
if (read_result.wait_for(std::chrono::seconds(1)) == 
    std::future_status::timeout)
{
  socket.cancel();
}
// Otherwise, the operation completed (with success or error).
else
{
  // If the operation failed, then read_result.get() will throw a
  // boost::system::system_error.
  auto bytes_transferred = read_result.get();
  // process buffer
}

为什么SO_RCVTIMEO无法使用

系统行为

SO_RCVTIMEO 文档指出,该选项仅影响执行套接字I/O的系统调用,例如read()recvmsg()。它不影响事件多路分解器,例如select()poll(),它们仅监视文件描述符来确定何时可以发生I/O而不会阻塞。此外,当确实发生超时时,I/O调用将无法返回-1,并将errno设置为EAGAINEWOULDBLOCK失败。

Specify the receiving or sending timeouts until reporting an error. [...] if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK [...] Timeouts only have effect for system calls that perform socket I/O (e.g., read(), recvmsg(), [...]; timeouts have no effect for select(), poll(), epoll_wait(), and so on.



当基础文件描述符设置为非阻塞时,如果没有立即可用的资源,则执行套接字I/O的系统调用将立即返回EAGAINEWOULDBLOCK。对于非阻塞套接字,SO_RCVTIMEO不会有任何影响,因为成功或失败后,调用将立即返回。因此,为了使SO_RCVTIMEO影响系统I/O调用,套接字必须处于阻塞状态。

Boost.Asio行为

首先,Boost.Asio中的异步I/O操作将使用事件多路分解器,例如select()poll()。因此,SO_RCVTIMEO不会影响异步操作。

接下来,Boost.Asio的套接字具有两种非阻塞模式的概念(两种模式均默认为false):
  • native_non_blocking() 模式大致对应于文件描述符的非阻塞状态。此模式影响系统I/O调用。例如,如果调用socket.native_non_blocking(true),则recv(socket.native_handle(), ...)可能会失败,并且errno设置为EAGAINEWOULDBLOCK。每当在套接字上启动异步操作时,Boost.Asio都会启用此模式。
  • non_blocking() 模式会影响Boost.Asio的同步套接字操作。当设置为true时,Boost.Asio会将基础文件描述符设置为非阻塞和同步Boost.Asio套接字操作可能因boost::asio::error::would_block失败(或等效的系统错误)。当设置为false时,即使基础文件描述符是非阻塞的,Boost.Asio也会阻塞,方法是轮询文件描述符并重新尝试系统I/O操作(如果返回EAGAINEWOULDBLOCK)。
  • non_blocking()的行为会阻止SO_RCVTIMEO产生所需的行为。假设socket.receive()被调用并且数据既不可用也不接收:
  • 如果non_blocking()为false,则每个SO_RCVTIMEO的系统I/O调用将超时。但是,Boost.Asio随后将立即阻止对文件描述符的轮询以使其可读,这不受SO_RCVTIMEO的影响。最终结果是调用者被阻止在socket.receive()中,直到接收到数据或发生故障(例如远程对等方关闭连接)为止。
  • 如果non_blocking()为true,则基础文件描述符也是非阻塞的。因此,系统I/O调用将忽略SO_RCVTIMEO,立即以EAGAINEWOULDBLOCK返回,从而导致socket.receive()失败,并以boost::asio::error::would_block失败。

  • 理想情况下,为了使SO_RCVTIMEO与Boost.Asio一起运行,需要将native_non_blocking()设置为false,以便SO_RCVTIMEO可以生效,但也需要将non_blocking()设置为true,以防止对描述符进行轮询。但是,Boost.Asio并不support this:

    socket::native_non_blocking(bool mode)

    If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.

    关于c++ - SO_RCVTIME和SO_RCVTIMEO不影响Boost.Asio操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410265/

    相关文章:

    通过默认 c'tor 进行 C++ pod 初始化

    c++ - C++中的字符串数组和Arraylist/list

    linux - 反病毒开发入门

    c++ - 重写映射迭代器以返回dynamic_casted值

    c++ - 使用 is_integral/BOOST_STATIC_ASSERT 限制模板实例化

    C++ 进程终止,状态为 -1073741510(0 分钟,2 秒)

    linux - 无法签署 RPM : RPM sign execution returned: '127'

    linux - 解释多线程程序的 Linux 时间命令结果 (%CPU > 100)

    c++ - 无法理解 multi_index

    c++ - 动态二维数组创建运行时错误