0

I am running c language code using a java application using java.lang.ProcessBuilder. If any output and error generated by this c language code, I am able to read those via process.getInputStream() and process.getErrorStream(). But in some cases (when exit code = 136 or 139) like if the code execution failed due to floating point error, I am not getting any error in process's error stream. So, I tried to run my c language code directly on shell and redirected stderr and stdout to seperate files. Code.c

#include<stdio.h>

int main() {
    int x = 1/0;
    return 0;
}

Command I am running:

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

As you can see above error is printing on shell only but not redirecting to err.log. Also, nothing is there in err.log. My question is why this is not printing in stderr stream? As per my understanding if it is not printing in stderr I will not be able to read it via process.getErrorStream. Whatever the error message generated by code execution, I wanted to show it to end user.

Aayush Jain
  • 183
  • 1
  • 11
  • 2
    The output likely isn't from the program itself, but either from the shell or the OS. – Some programmer dude Feb 11 '22 at 11:43
  • 2
    The process running your code does not output this message, so it doesn't go either to a redirected file or any stream in the Java parent. When your code gets an unhandled signal, it just exits with an error status of 128 plus the signal number (SIGFPE=8+128=136 or SIGSEGV=11+128=139). **Your shell prints the message** when it receives this exit status, and the _shell_ did not have its I/O redirected in any way. Java returns the status to your code, which can decide what if anything to print. – dave_thompson_085 Feb 11 '22 at 11:49
  • @dave_thompson_085 That could be an answer rather than a comment :) – Thomas Feb 11 '22 at 11:50

1 Answers1

1

As dave_thompson_085 comments, the Floating point exception (core dumped) message is from the Shell rather than the program.

This is a test program:

#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

When the float exception occurs, it is captured by the OS and forced to exit.

Zongru Zhan
  • 546
  • 2
  • 8