Use GDB to debug a C++ program called from a shell script

26,408

Solution 1

There are two options that you can do:

  1. Invoke GDB directly within the shell script. This would imply that you don't have standard in and standard out redirected.

  2. Run the shell script and then attach the debugger to the already running C++ process like so: gdb progname 1234 where 1234 is the process ID of the running C++ process.

If you need to do things before the program starts running then option 1 would be the better choice, otherwise option 2 is the cleaner way.

Solution 2

In addition to options mentioned by @diverscuba23, you could do the following:

gdb --args bash <script>

(assuming it's a bash script. Else adapt accordingly)

Solution 3

Modify the c++ application to print its pid and sleep 30 seconds (perhaps based on environment or an argument). Attach to the running instance with gdb.

Solution 4

I would probably modify the script to always call gdb (and revert this later) or add an option to call gdb. This will almost always be the easiest solution.

The next easiest would be to temporarily move your executable and replace it with a shell script that runs gdb on the moved program. For example, in the directory containing your program:

$ mv program _program
$ (echo "#!/bin/sh"; echo "exec gdb $PWD/_program") > program
$ chmod +x program

Solution 5

Could you just temporarily add gdb to your script?

Share:
26,408
CuriousMind
Author by

CuriousMind

Updated on June 26, 2020

Comments

  • CuriousMind
    CuriousMind almost 4 years

    I have a extremely complicated shell script, within which it calls a C++ program I want to debug via GDB. It is extremely hard to separate this c++ program from the shell since it has a lot of branches and a lot of environmental variables setting.

    Is there a way to invoke GDB on this shell script? Looks like gdb requires me to call on a C++ program directly.