从外部过程管道阅读时,fgets卡在
我正在从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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论