在Windows上执行进程并获取结果
Execute process and get result on Windows
我有一段代码,它执行一个过程并检索结果。
namespace {
FILE* really_popen(const char* cmd, const char* mode) {
#ifdef _MSC_VER
return _popen(cmd, mode);
#else
return popen(cmd, mode);
#endif
}
void really_pclose(FILE* pipe) {
#ifdef _MSC_VER
_pclose(pipe);
#else
pclose(pipe);
#endif
}
std::string ExecuteProcess(std::string cmd) {
FILE* pipe = really_popen(cmd.c_str(), "r");
if (!pipe) throw std::runtime_error("Could not invoke command " + cmd);
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
really_pclose(pipe);
return result;
}
}
这在Linux上对我来说很好,但在Windows上,它有一个可怕的死锁习惯——似乎fgets
永远不会返回。我已经研究了CRT源,fgets
最终委托给ReadFile
,它永远不会返回。
如果我从命令行调用该命令,它会在一秒钟内返回。
如何在不使父级死锁的情况下读取Windows上的输出?
如果子级尚未退出,那么对fgets((的调用将不会退出,因此需要解决子级未退出的原因。在这种情况下,最有可能的原因是孩子挂断了,因为它没有标准的输入。
如果是这个问题,您可以通过将管道模式更改为"rw"来解决它。你通常不需要用额外的管道做任何事情,它只需要在那里。
(正如您在评论中提到的,这个问题也可以通过使用命令shell重定向来解决,为子级提供NUL
的句柄作为标准输入。(
相关文章:
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- C++ 获取函数在常量引用中按值返回的结果
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- 从 C++ 中的 URL 获取结果
- 如何从主.cpp中的cpp文件中获取功能结果?
- 如何从 regexp_match() 中获取结果
- 无法在 WinRT 中获取异步操作结果 (Windows::Foundation::IAsyncOperating 接口
- mysql++(mysqlpp):如何在迭代之前通过UseQueryResult使用fetch_row获取结果中的行数
- QDialog exec() 并获取结果值
- 从非线程阻塞消息框获取结果
- 如何使用 QueryPerformanceCounter 在几秒钟内获取结果
- C++执行命令行并获取结果
- C++模板方法和获取结果的设计
- 如何从服务器获取结果
- 从返回类型的函数中获取结果'void'而结果变量是输入参数之一 - C++
- 从具有可变数量模板化参数的模板化类中的特定基类获取结果
- 取消引用无效指针,然后获取结果的地址
- 在Windows上执行进程并获取结果
- 用c++运行一个进程,过滤输出,获取结果代码,同时获取系统错误
- 通过usb从控制器获取结果失败