bash脚本在使用popen()时不返回代码以调用C ++程序

bash script not returning return code to calling c++ program when using popen()

本文关键字:代码 返回 调用 程序 脚本 popen bash      更新时间:2023-10-16

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

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;
}

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

进程的终止状态代码由pclose返回。当前,您放弃对pclose调用的返回值