msf1013
msf1013

Reputation: 419

Redirect execution errors to file c++

How can I redirect execution errors of a c++ executable in bash? I've found that 2> helps while trying identify compilation errors:

g++ example.cpp 2> compErr.txt

But running the executable with that command still sends the errors to stdout:

$ ./a.out 2> e.txt
Floating point exception (core dumped)

Upvotes: 1

Views: 1581

Answers (2)

msf1013
msf1013

Reputation: 419

I found something that worked in my terminal, here: http://bytes.com/topic/c/answers/822874-runtime-error-stderr-gcc-ubuntu-bash

In summary, a participant explained:

In this particular case, the reason that the string "Floating point exception" is not >redirected is that it is not produced by the process that runs ./{file} or anything that it invokes. Instead,it is being produced by the command-interpreter itself.

You can see this by telling the command interpreter to run another command interpreter, redirecting this sub-interpreter's error output. However, a bit of a >trick is required:

$ bash -c './{file}; true' >out 2>err    
$ cat out
$ cat err
bash: line 1: 28106 Floating point exception./test_fail

Upvotes: 3

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

Actually, the error "Floating point exception (core dumped)" does not come from the executable but from the shell! The messages from bash won't be suppressed by output redirection but there is a flag to enable/disable these messages.

You can install signal handlers for some of the errors which would cause the program to exit and write something to a suitable destination there. Some signals can't be intercepted and some other are hard to handle. That's the approach you can do from inside your code.

If you want to go further you could fork() your program first thing and have the actual work done in the child process. The parent process would essentially just waitpid() for the child process and use the information in the result structure received to report errors to a file.

Upvotes: 7

Related Questions