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

问题描述 投票:0回答:1

我写了一个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)
c++ shell
1个回答
3
投票

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

想一想:该计划已经死亡。它如何产生额外的输出?

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

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

( ./test ) 2>error.txt
© www.soinside.com 2019 - 2024. All rights reserved.