jinge jinge - 3 years ago 278
Bash Question

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

I wrote a C++ demo


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)

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download