简体   繁体   English

为什么崩溃时在外壳中运行的可执行文件输出到stdout而不是stderr?

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

I wrote a C++ demo test.cpp like: 我写了一个C ++演示test.cpp像这样:

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

then compiled it 然后编译

$ g++ test.cpp -o test

then run it in shell: 然后在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. 我希望将错误消息重定向到error.txt,但它们仍会通过stdout在屏幕上打印。 Why did that happen? 为什么会这样呢?

The output shows as below: 输出结果如下:

Floating point exception (core dumped)

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 . 实际上,即使将程序的 stdout和stderr 重定向到/dev/null ,您也会观察到输出。

If you create a sub-shell and redirect its stderr, you'll see the error message redirected: 如果创建子外壳并重定向其stderr,您将看到重定向的错误消息:

( ./test ) 2>error.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM