mercredi 1 décembre 2021

Why does std::system return a different exit status when I redirect the output to a file?

I am trying to check the exit status of a process executed via std::system in C++ and I found that when a process aborts I end up with a different exit status depending on whether I redirect STDOUT to a file or not.

Here is an example:

#include <iostream>

using namespace std;

int main()
{
    int status1;
    try {
        status1 = system("my_subprocess");
    } catch(...) {}

    int status2;
    try {
        status2 = system("my_subprocess >out.txt");
    } catch(...) {}

    cout << "STATUS1: " << status1 << endl;
    cout << "STATUS2: " << status2 << endl;
}

And the code for my_subprocess which intentionally aborts is shown here:

int main()
{
    throw;
}

The output I get from running the test program is:

terminate called without an active exception
terminate called without an active exception
sh: line 1: 10572 Aborted                 (core dumped) my_subprocess > out.txt
STATUS1: 134
STATUS2: 34304

As you can see, simply redirecting STDOUT drastically altered the returned status code from the process.

What is happening here and why does the exit code change?

Aucun commentaire:

Enregistrer un commentaire