Esash
Esash

Reputation: 137

commands to gdb from C program

I am newbie to UNIX programs. I have encountered a situation wherein I have to issue commands to gdb from my C program. I have a C program which invokes another C program by forking a new child process. I need to debug this child C program and hence, I used system command to call gdb process on this C program. But I get a gdb prompt which I do not want. I want to issue commands to the gdb from my parent C program. Is there a way to issue commands to gdb from a C program ?

Please reply.

Thanks a lot.

Esash

Upvotes: 5

Views: 1041

Answers (3)

Man Vs Code
Man Vs Code

Reputation: 1057

Theres also the follow on fork gdb option. This will attach to the child process immediately.

set follow-fork-mode mode

so,

set follow-fork-mode child

Upvotes: 0

Employed Russian
Employed Russian

Reputation: 213375

There are several ways to "drive" GDB programmatically.

If you just want to issue one command, e.g. to find out why the child crashed, you can do something like this:

gdb --batch -ex where /path/to/child <pid-of-child>

If there are more commands then you are willing to put on command line, you could write them to a temporary file, and ask gdb to execute them:

gdb --batch -x /path/to/commandfile /path/to/child <pid-of-child>

Neither of the above allows you to perform programmatic (if ... then do-something-in-gdb else do-something-else-in-gdb) control.

For that you may want to either exercise GDB's machine interface (MI), or use the embedded Python interpreter.

Upvotes: 3

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95449

If you need to debug the child process, you don't necessarily need to invoke the child with GDB when you fork+exec. As long as you have the PID of the child process, you can use the "attach" command in GDB to attach to the running child process. Basically, you would start GDB like:

 $ gdb
 (gdb) attach pid-of-child

In the above, replace pid-of-child with the PID of the child process, and there you go, you can debug the child process from interactive GDB, without the parent process needing to deal with GDB at all.

Upvotes: 4

Related Questions