【问题标题】:bash script not returning return code to calling c++ program when using popen() [duplicate]bash脚本在使用popen()时不返回返回码来调用c++程序[重复]
【发布时间】:2018-09-28 13:51:04
【问题描述】:

我有一个在 bash 脚本中调用的 python 脚本,如下所示:

python3 CheckRef.py --reference $EXPECTED --result $RESULT.npy
echo "return code = $?"

脚本从 python 脚本打印正确的返回码。例如,如果 python 脚本返回-2,它会打印254

但是,当我在 c++ 程序中调用 bash 脚本时,返回码是空的。它应该返回-2

testClass test;
auto result = test.execute(command.c_str());
std::cout << "result is " << result << std::endl;

谁能告诉我我做错了什么?

这是execute()函数

std::string testClass::execute(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++ bash shell popen


【解决方案1】:

您的execute 函数返回一个包含命令输出的字符串,而不是终止代码。

进程的终止状态码由pclose返回。目前您丢弃了对pclose的调用的返回值

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    相关资源
    最近更新 更多