4

I'm debugging my program with gdb. I'm able to have a non-interactive debug using the -x options.

gdb -x gdbinit ./myprogram

Content of gdbinit file:

handle SIGINT pass nostop noprint
handle SIGQUIT pass nostop noprint
handle SIGUSR1 pass nostop noprint
handle SIGUSR2 pass nostop noprint
run
backtrace
quit

The four signals aren't handled by gdb because they are needed by my program to work properly.

The backtrace command is useful to have a backtrace after a crash.

The quit command make gdb exit after the program execution, even if it has crashed.

I want to exit automatically only if the program finishes successfully. In other cases, gdb should be available to analize backtraces and other things.

How can gdb exit ONLY if the program exits WITHOUT ERROR?

Alessandro Pezzato
  • 8,603
  • 5
  • 45
  • 63

1 Answers1

11

Use the $_exitcode GDB convenience variable. In your gdb script above, replace:

run

with:

set $_exitcode = -1
run
if $_exitcode != -1 
    quit
end

and remove the quit line at the end should work. Using -1 as an impossible value works since in POSIX only the lower 8 bits of the exit status can be used. (see WEXITSTATUS() in wait(2)).

To uses the GDB Python API to accomplish the same thing, see here.

Community
  • 1
  • 1
scottt
  • 7,008
  • 27
  • 37
  • You can avoid the line explicitly setting exitcode to -1 by changing the condition to `if ! $_isvoid ($_exitcode)` – Fraser Jul 26 '23 at 18:01