Shailesh Tainwala
Shailesh Tainwala

Reputation: 6507

Return value of system() function call in C++, used to run a Python program

I am working on Linux with code that makes a system() call to run a python program. I am interested in the value returned by this function call to understand how the python program execution went.

So far, I have found 3 results:

This does not fit with what I've read about system() function.

Furthermore, the code for the python program being invoked shows that it exits with sys.exit(2) when any error is encountered, and sys.exit(0) when execution completes successfully.

Could anyone relate these two? Am I interpreting the return value in a wrong manner? Is there some Linux processing involved that takes the argument of the sys.exit() function of the python program and returns value of system() based on it?

Upvotes: 15

Views: 40634

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

The exit code of the program you call can be fetched with WEXITSTATUS(status) as per the manual page. Also see the manual page for wait.

int status = system("/path/to/my/program");
if (status < 0)
    std::cout << "Error: " << strerror(errno) << '\n';
else
{
    if (WIFEXITED(status))
        std::cout << "Program returned normally, exit code " << WEXITSTATUS(status) << '\n';
    else
        std::cout << "Program exited abnormaly\n";
}

Upvotes: 23

Related Questions