Linux – Can you get any program in Linux to print a stack trace if it segfaults

linuxsegmentation-fault

If I run a program from the shell, and it segfaults:

$ buggy_program
Segmentation fault

It will tell me, however, is there a way to get programs to print a backtrace, perhaps by running something like this:

$ print_backtrace_if_segfault buggy_program
Segfault in main.c:35
(rest of the backtrace)

I'd also rather not use strace or ltrace for that kind of information, as they'll print either way…

Best Answer

There might be a better way, but this kind of automates it.

Put the following in ~/backtrace:

backtrace
quit

Put this in a script called seg_wrapper.sh in a directory in your path:

#!/bin/bash
ulimit -c unlimited
"$@"
if [[ $? -eq 139 ]]; then
    gdb -q $1 core -x ~/backtrace
fi

The ulimit command makes it so the core is dumped. "$@" are the arguments given to the script, so it would be your program and its arguments. $? holds the exit status, 139 seems to be the default exit status for my machine for a segfault.

For gdb, -q means quiet (no intro message), and -x tells gdb to execute commands in the file given to it.

Usage

So to use it you would just:

seg_wrapper.sh ./mycommand and its arguments 

Update

You could also write a signal handler that does this, see this link.