从外部过程管道阅读时,fgets卡在

发布于 2025-02-03 05:01:12 字数 839 浏览 4 评论 0原文

我正在从popen中调用iperf3,然后从其输出中读取到字符串中。

#include <stdio.h>
#include <iostream>

using namespace std;

int main() {
  string peer_ip = "localhost";

  string iperf_cmd = "iperf3 -c " + peer_ip + " -t 1" + " -R 2>&1";
  string iperf_out;
  char iperf_buff[2];

  FILE *iperf_d = popen(iperf_cmd.c_str(), "r");
  while (fgets(iperf_buff, 2, iperf_d) != nullptr)
    iperf_out += iperf_buff;
  pclose(iperf_d);

  cout << iperf_out << "\n";
}

这大多数时候都起作用。

但是,当网络非常慢时,我的fgets被卡住了,并且程序切勿从iperf3中打印输出。这是为什么?

来自MAN FGETS(3)

fgets()读取最多比流的大小字符少。 并将它们存储到s指向的缓冲区中。阅读停止 在EOF或NEWLINE之后。如果读取新线,则将其存储在 缓冲区。最后一个终止null字节('\ 0')是在上次之后存储的 缓冲区中的字符。

请注意,我的缓冲区长2个字节。

I'm calling iperf3 from via popen and read from its output into a string.

#include <stdio.h>
#include <iostream>

using namespace std;

int main() {
  string peer_ip = "localhost";

  string iperf_cmd = "iperf3 -c " + peer_ip + " -t 1" + " -R 2>&1";
  string iperf_out;
  char iperf_buff[2];

  FILE *iperf_d = popen(iperf_cmd.c_str(), "r");
  while (fgets(iperf_buff, 2, iperf_d) != nullptr)
    iperf_out += iperf_buff;
  pclose(iperf_d);

  cout << iperf_out << "\n";
}

This works most of the time.

However, when the network is is very slow, my fgets gets stuck and program never prints the output from iperf3. Why is that?

From man fgets(3):

fgets() reads in at most one less than size characters from stream
and stores them into the buffer pointed to by s. Reading stops
after an EOF or a newline. If a newline is read, it is stored into
the buffer. A terminating null byte ('\0') is stored after the last
character in the buffer.

Note that my buffer is 2 bytes long.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文