1

I have a python script that gets called in a bash script like this:

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

The script prints the correct return code from the python script. For example it prints 254 if the python script returns -2.

However, when I call the bash script in a c++ program the return code is empty. It should be returning -2.

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

Could anybody advise what I'm doing wrong?

This is the function 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;
    }
cherry aldi
  • 327
  • 1
  • 10
  • The last command in the bash script is `echo`. Its exit status is `0`. – Barmar Sep 28 '18 at 14:11
  • [Why `while (!feof(file))` is always wrong](https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – Barmar Sep 28 '18 at 14:12

1 Answers1

1

Your execute function returns a string that contains the output of the command, not the termination code.

The termination status code of the process is returned by pclose. Currently you discard the return value of your call to pclose

eerorika
  • 232,697
  • 12
  • 197
  • 326