调用send()可以无错误地关闭应用程序

问题描述 投票:0回答:1

我有一个客户端应用程序通过TCP发送数据。在某些时候,对send()的调用返回时没有发送所有可用字节,下一次调用send会关闭应用程序而不会出现任何错误。

调用send()的循环如下所示:

  // m_buf is an std::vector of size 65536
  auto total_bytes = fill_buffer(m_buf.data(),m_buf.size());
  while(total_bytes > 0){
    // m_socket is a straightforward wrapper around a socket descriptor that
    // throws if a call to send() returns an error.
    auto total_bytes_sent = m_socket.send(m_buf.data(),total_bytes);
    auto remaining_bytes  = total_bytes - total_bytes_sent;
    while(remaining_bytes > 0){
      total_bytes_sent += m_socket.send(m_buf.data()+total_bytes_sent,remaining_bytes);
      remaining_bytes   = total_bytes - total_bytes_sent;
    }
    total_bytes = fill_buffer(m_buf.data(),m_buf.size());
  }

我也有一些调试打印:

send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 8127
send: remaining_bytes 57409
[computer@localhost test]$

最后,send()被调用以发送remaining_bytes,但调用永远不会返回(也没有捕获异常)并且应用程序关闭。

c++ posix centos7
1个回答
1
投票

一种可能性是你从send()获得错误返回,但你没有检查-1。这可能会使total_bytes_sent成为负数,这会将您的第二次发送置于无效内存中。

© www.soinside.com 2019 - 2024. All rights reserved.