c++ - 调用 send() 无错误地关闭应用程序

标签 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() 来发送 remaining_bytes,但调用永远不会返回(也没有捕获到异常)并且应用程序关闭。

最佳答案

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

关于c++ - 调用 send() 无错误地关闭应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162779/

相关文章:

c++ - 重载赋值运算符以返回 std::vector

posix - "posix isolation"是什么?

c - 如何共享现有内存?

linux - 无法终止 fork 进程

linux - 如何在 Centos 7 上安装 konsole?

c++ - 如何在 C++ 中限制模板参数?

C++ : DirectX Texture is Misaligned/Shifted

c++ - 更改 QAudioOutput 音量后出现噪音

ssh - 有没有办法允许来自 Centos 上特定机器的 SSH?

linux - 如何在centos 7上重新加载pythonic服务?