C ++:执行命令并返回输出会导致断言失败

问题描述 投票:1回答:2

我正在开发一个项目,要求我使用adb install以编程方式安装Android .apk。我还需要获取结果输出以便稍后使用。我有以下通用函数来执行命令并将输出作为字符串返回:

std::string exec(const char* command) {
    std::string output = "";
    const int bufferSize = 100;

    FILE *pipe;
    char buffer[bufferSize];

    pipe = _popen(command, "r");
    if (pipe == NULL) {
        exit(1);
    }
    while (fgets(buffer, bufferSize, pipe) != NULL) {
        output += buffer;
    }
    _pclose(pipe);

    return output;
}

当命令执行并正确返回输出时,使用此函数执行adb install时出现以下错误:

调试断言失败!

程序:...(我的.exe)文件:minkernel \ crts \ ucrt \ src \ appcrt \ lowio \ read.cpp行:258

表达式:static_cast(source_buffer)== static_cast(result_buffer)

我在网上搜索了这个错误,没有任何结果。以下是导致断言失败的行:

while (fgets(buffer, bufferSize, pipe) != NULL) {

谁能告诉我这里发生了什么,我能解决这个问题吗?

android c++ assertions
2个回答
0
投票

也许以下内容是相关的(来自microsoft docs)

如果在Windows程序中使用,_popen函数将返回一个无效的文件指针,该指针会导致程序无限期地停止响应。 _popen在控制台应用程序中正常工作。要创建重定向输入和输出的Windows应用程序,请参阅在Windows SDK中创建具有重定向输入和输出的子进程。

尝试以下https://msdn.microsoft.com/library/windows/desktop/ms682499


0
投票

得到了同样的问题,并通过设置模式修复为二进制(添加'b'):

_popen(xxx, "rb");
© www.soinside.com 2019 - 2024. All rights reserved.