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

烂漫一生 提交于 2019-12-11 06:49:21

问题


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.

来源:https://stackoverflow.com/questions/40408586/call-to-fgets-on-stream-generated-by-popen-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!