我写了一个C ++演示test.cpp

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


然后编译

$ g++ test.cpp -o test


然后在shell中运行它:

$ ./test 2>error.txt


我希望将错误消息重定向到error.txt,但它们仍会通过stdout在屏幕上打印。为什么会这样呢?

输出结果如下:

Floating point exception (core dumped)

最佳答案

因为错误消息不是由程序生成的。它由操作系统生成。

想想:程序已经死了。如何产生额外的输出?

实际上,即使将程序的stdout和stderr都重定向到/dev/null,您也会观察到输出。

如果创建子外壳并重定向其stderr,您将看到重定向的错误消息:

( ./test ) 2>error.txt

关于c++ - 为什么崩溃时在 shell 中运行的可执行文件输出到stdout而不是stderr?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47941292/

10-11 23:10
查看更多