c-为什么没有在stderr上打印浮点错误消息



我正在使用java.lang.ProcessBuilder使用java应用程序运行c语言代码。如果这个c语言代码产生了任何输出和错误,我可以通过process.getInputStream()process.getErrorStream()读取这些输出和错误。但在某些情况下(当退出代码=136或139时(,比如由于floating point error导致代码执行失败,我不会在进程的错误流中得到任何错误。因此,我尝试直接在shell上运行c语言代码,并将stderr和stdout重定向到不同的文件。代码.c

#include<stdio.h>
int main() {
int x = 1/0;
return 0;
}

我正在运行的命令:

# gcc Code.c -o Code.out -std=c99
# ./Code.out 2>err.log 1>out.log
Floating point exception (core dumped)

正如您所看到的,上面的错误只是在shell上打印,而不是重定向到err.log。此外,err.log中没有任何内容。我的问题是,为什么它没有在stderr流中打印?根据我的理解,如果它没有在stderr中打印,我将无法通过process.getErrorStream读取它。无论代码执行产生什么错误消息,我都想向最终用户显示它。

dave_thompson_085注释,Floating point exception (core dumped)消息来自Shell,而不是程序。

这是一个测试程序:

#include<stdio.h>
int main() {
fprintf(stdout, "normal output, %dn", __LINE__);
fprintf(stderr, "error output, %dn", __LINE__);
fflush(stdout);
fflush(stderr);
int x = 1/0;
fprintf(stdout, "normal output, %dn", __LINE__);
fprintf(stderr, "error output, %dn", __LINE__);
fflush(stdout);
fflush(stderr);
return 0;
}
# gcc code.c -o Code -std=c99
# ./Code  2>err.log 1>out.log
normal output, 4
error output, 5
Floating point exception (core dumped)
# cat out.log
normal output, 4
$cat err.log
error output, 5

当发生float异常时,操作系统会捕获该异常并强制退出。

最新更新