簡體   English   中英

為什么不在 stderr 上打印浮點錯誤消息?

[英]Why floating point error message is not printing on stderr?

我正在使用 java.lang.ProcessBuilder 使用java.lang.ProcessBuilder應用程序運行 c 語言代碼。 如果有任何 output 和此 c 語言代碼生成的錯誤,我可以通過process.getInputStream()process.getErrorStream()讀取它們。 但在某些情況下(當退出代碼 = 136 或 139 時),例如代碼執行因floating point error而失敗,我在進程錯誤 stream 中沒有收到任何錯誤。因此,我嘗試直接在 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 stream 中打印? 根據我的理解,如果它沒有在 stderr 中打印,我將無法通過 process.getErrorStream 讀取它。 無論代碼執行生成什么錯誤消息,我都想將其顯示給最終用戶。

正如 dave_thompson_085 評論的那樣, Floating point exception (core dumped)消息來自 Shell 而不是程序。

這是一個測試程序:

#include<stdio.h>

int main() {
    fprintf(stdout, "normal output, %d\n", __LINE__);
    fprintf(stderr, "error output, %d\n", __LINE__);
    fflush(stdout);
    fflush(stderr);

    int x = 1/0;

    fprintf(stdout, "normal output, %d\n", __LINE__);
    fprintf(stderr, "error output, %d\n", __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異常發生時,會被OS捕獲並強制退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM