调用send()可以关闭应用程序而不会出现错误

时间:2019-03-14 12:39:30

标签: c++ posix centos7

我有一个客户端应用程序通过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()来发送剩余的字节,但是该调用永不返回(也没有捕获到异常),并且应用程序关闭。

1 个答案:

答案 0 :(得分:1)

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