0

I made a C program that would throw segmentation fault error whenever I run it. And then I made a bash script as follows:

cat input.txt | ./a.out 1> output.txt 2> error.txt
cat error.txt

The output of the second line should have been something like segmentation error (core-dumped) But instead it's a blank file.

How do I capture the runtime errors of a C program?

3
  • What is the operator precedence of the pipe and stderr-redirection operators? Commented Oct 16, 2016 at 22:11
  • @Dai , sorry, I didn't get your question. Can you simplify it? Commented Oct 16, 2016 at 22:15
  • Avoid unnecessary use of cat (e.g. ./a.out <input.txt >output.txt 2>error.txt Commented Oct 16, 2016 at 23:25

1 Answer 1

2

Your problem stems from the fact that the Segmentation fault (core dumped) message is not generated by your program, it is generated by the shell in which you can the a.out command. The process looks approximately like this:

  • Your program generates a segfault
  • Your program receives a SIGSEGV signal
  • Your program exits
  • The wait() system call executed by your shell exits with a status code that indicates your program exited abnormally due to a SIGSEGV signal.
  • The shell prints an error message

This is discussed in somewhat more detail in this answer.

If you want to capture this output, you can try something like:

$ sh -c 'trap "" 11; ./a.out' 1> output.txt 2> error.txt
$ cat error.txt
Segmentation fault (core dumped)

This will run your code in a subprocess and will inhibit the default handling of the segfault by the shell.

Sign up to request clarification or add additional context in comments.

2 Comments

What's does the "" 11; do inside the trap?
man bash has the answer: "If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.