I ran an executable in bash

./code > log

It shows occasional error messages on terminal whereas all printf statements go into log file. I re-run it like below

./code >& log

Now, the occasional error messages also go into log. But if there is a segmentation fault, it is still shown on terminal. Why? How to make the message Segmentation fault (core dumped) go into the log file?

user$ bash --version

GNU bash, version 4.2.24(1)-release (i686-pc-linux-gnu)


A segmentation fault is a signal, if you are not catching this then your program will be terminated and your shell will print this to its stderr (rather than your program's stderr).

It is possible for either your program or the shell to take specific actions when this occurs, either by the program catching the signal or your shell trapping the SIGCHILD signal and then checking your child's exit status.

  • 1
    @user13107 help trap – Carlos Campderrós Oct 30 '12 at 8:31
  • 2
    yup. got it. if anyone's interested, here's what i did pastebin.com/QyeJYYHC – user13107 Oct 30 '12 at 9:50
  • 1
    The shell trap command traps signals sent to the shell. So it won't work to catch the one being sent to your program. – derobert Oct 31 '12 at 11:36
  • 1
    @warl0ck it is possible to catch a segfault in the same way you catch any signal, however this can lead to undefined behavior, but if you know what you are doing you may be able to at least die in a sensible way. The OP wanted to print to stderr, in this case catching the segfault and printing is safe. – cjh Oct 31 '12 at 18:43
  • 1
    @warl0ck: you can, it's just a very bad idea to do anything in the handler but log and exit. There are some specialized use cases though. – Linuxios Nov 5 '12 at 22:38

The “segmentation fault” message is printed to stderr, but it's the shell's standard error, not the program's standard error. The shell prints this message when it detects that the program has terminated due to a signal.

You can silence the message by redirecting stderr around the part of the shell script that runs the program:

{ ./code; } >&log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.