Call to `fgets` on stream generated by `popen` han

2019-08-04 05:34发布

问题:

I have an application that uses the following piece of code to run a cmd and get its output:

std::string cmd = "ps -a -x -o pid,ppid,state,command | grep myProcess | grep -v 'grep' | awk '{ print $1, $2, $3 }'";
char buf[BUF_SIZE];
std::stringstream output;
std::string err;
int exitCode;
FILE* proc = popen(cmd.c_str(), "r");

if (proc == NULL) {
    exit(1);
}
while (fgets(buf, BUF_SIZE, proc) != NULL) {
    output << buf;
}
exitCode = pclose(proc);

std::string outputStr = output.str();

The problem I am having is that the function would get stuck on the fgets function randomly. I cannot consistently make it to get stuck.

How can that happen?

The code is running under macOS 10.10 and upwards.