Gdb how to execute target program from script

I want to debug a program using gdb. But I call this program through a script.

How to use gdb? The script is long and I am unable to directly invoke the program directly using command line arguments from gdb.

Also, the process created when the script was run is short-lived, so you cannot attach gdb to the process.

What I want to do is something like: run gdb with this program, add my breakpoints, then execute the script (FYI - it also takes arguments), and then when it reaches the breakpoint, do whatever I want.

I looked at the shell option in gdb, but it spawns a new shell if I am not mistaken and return to gdb when it is done. This is not what I want.

Please let me know if there is a better way.

+4
source share
2 answers

There are several ways.

A really old-fashioned way is to crack a loop in your program main, for example:

volatile int zzz;
...
int main() {
  while (!zzz) sleep (1);

Then run the script. In a separate window, run gdb for the program you want to debug, and use it attachto join the sleeping program. Then you can set breakpoints, etc. And finally

(gdb) set var zzz = 1
(gdb) cont

A little newer ("new", as in "he has been in gdb for at least 10 years"), so edit your script and put gdb --argsin front of the program you want to debug. However, this method does not always work. By the way, it does not handle redirects.

, . "" . :

$ gdb /bin/sh  # or whatever runs your script
(gdb) set args arguments-to-the-script
(gdb) set detach-on-fork off
(gdb) set target-async on
(gdb) set non-stop on
(gdb) set pagination off

- :

(gdb) add-inferior -exec program-you-want-to-debug

... . run - !

+7

, .

  • yourprog yourprog.real. script yourprog, gdb --args yourprog.real "$@".
  • yourprog invoke gdb pid, sleep .
+1

All Articles