【问题标题】:Calling send() closes the applicaiton without error调用 send() 关闭应用程序而不会出错
【发布时间】:2019-03-14 12:39:29
【问题描述】:

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

【问题讨论】:

  • 请提供minimal reproducible example。您发布的输出不是来自您显示的代码
  • "如果调用 send() 返回错误则抛出。"如果你没有捕捉到你的程序将终止的异常,afaik 在这种情况下出现的消息只是编译器对你很好,但不是强制性的
  • 原始源代码包含许多文件,提供完整且最小的示例有点不兼容。异常处理得当,但我不能包含导致异常处理程序的所有源代码。
  • 在 mcve 中“完成”是指“有足够的代码来重现问题”,而不是“发布所有代码”中的“完成”。至少您可以发布与输出匹配的代码,而不是不相关的代码和输出
  • 顺便说一句,创建 mcve 是一个非常有用的调试工具。如果您无法隔离问题并生成 mcve,那么您将遇到更普遍的问题

标签: c++ posix centos7


【解决方案1】:

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

【讨论】:

  • 如果对 posix send() 的底层调用返回 -1,则 m_socket.send() 方法会引发异常。这些异常被捕获在位于顶级方法中的处理程序中,该方法导致 m_socket.send()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
相关资源
最近更新 更多