jinge
jinge

Reputation: 865

Why an executable running in shell output to stdout instead of stderr when crashes?

I wrote a C++ demo test.cpp like:

int main()
{
    int num = 1 / 0;
}

then compiled it

$ g++ test.cpp -o test

then run it in shell:

$ ./test 2>error.txt

I expected the error messages to be redirected to error.txt, but they still print on the screen through stdout. Why did that happen?

The output shows as below:

Floating point exception (core dumped)

Upvotes: 0

Views: 169

Answers (1)

iBug
iBug

Reputation: 37257

Because the error message is not generated by the program. It is generated by the operating system.

Think: the program has died already. How can it generate extra output?

In fact, you'll observe output even if you redirect both stdout and stderr of the program to /dev/null.

If you create a sub-shell and redirect its stderr, you'll see the error message redirected:

( ./test ) 2>error.txt

Upvotes: 3

Related Questions