我有这个代码,我尝试用popen打开一个进程,得到它的输出并保留以后,在从proc读取的每个char之后我验证是否已经过了一定时间并且如果是,我放弃并关闭处理。 问题是,如果由于某种原因进程完全没有输出但是打开并运行,我将永远无法验证我的超时,因此循环将永远不会退出。 有什么建议可以解决这个问题吗?
char buffer[1024];
FILE *proc; //we need a file descriptor for the process
proc = popen(commandLine.c_str(),"r"); // We never pipe data into spawned processes so second parameter is always "r"
if (!proc)
return -1; //if it does not work we return right away
std::time_t startTime = std::time(NULL);
while (!feof(proc))
{
if (fgets(buffer, 1, proc) != NULL) //read until there is something to read
{
output->append(buffer);
std::time_t currTime = std::time(NULL);
int seconds = std::difftime(currTime,startTime);
if (seconds >= timeout) break;
}
else
break;
}
int closeFd = pclose(proc);
int exitCode = WEXITSTATUS(closeFd);
return exitCode;