使用_Popen Windows时问题

Issue when using _popen windows

本文关键字:问题 Windows Popen 使用      更新时间:2023-10-16

你好,我尝试使用_popen运行执行Windows命令,其工作在Console的VC 中正常。

虽然我在C 构建器中使用的代码相同的代码vcl表格popen return null指针?

vc

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = _popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    }
    catch (...) {
        _pclose(pipe);
        throw;
    }
    _pclose(pipe);
    return result;
}

c 建筑商与上述相同

void __fastcall TForm2::btn_adb_readInfoClick(TObject *Sender) {
    const char* cmd = "D:\adb\adb.exe devices";
    char buffer[128];
    std::string result = "";
    FILE* pipe = _popen(cmd, "r"); // always null
    char* er = strerror(errno);
    try
    {
        if (!pipe) throw std::runtime_error("popen() failed!");
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    }
    catch (std::exception &ex) {
        _pclose(pipe);
        throw;
    }
    _pclose(pipe);
}

_popen状态的MSDN文档:

如果在Windows程序中使用,则_popen功能返回无效的 文件指针导致程序无限期停止响应。 _popen在控制台应用程序中正常工作。

我假设C 构建器正在创建Windows应用程序而不是控制台应用程序。