fgets stuck when reading from an external process pipe

255 Views Asked by At

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.

0

There are 0 best solutions below