30
votes

I am debugging a program using gdb. Whenever I miss a breakpoint or decide to add another watchpoint, I have to kill the process and rerun it. In order to attach the existing gdb to it, I use attach <pid>. However, I have to find out the pid of the new process.

The way I do that today is to suspend gdb, get the pid with ps -C <program_name> and then return to gdb to attach to it.

Is there any way to run a unix command from the gdb command prompt without exiting to the shell, so that I could do something like this from inside gdb:

attach `ps -C <program_name>`

I am working on linux.

4

4 Answers

25
votes

(gdb) help shell
Execute the rest of the line as a shell command. With no arguments, run an inferior shell.

After finish, you can use 'exit' to return to gdb.

18
votes
gdb$ shell

shell$ execute_your_commands 

shell$ exit

gdb$ you_have_returned_back_to_gdb_prompt
10
votes

You can just use shell followed by the command you want to execute, e.g.:

gdb$ shell g++ tsort.c -o tsort

This is just a short form of the previous answer.

5
votes

Just to expand on the accepted answer, the shortcut for shell is !.

(gdb) help !

Execute the rest of the line as a shell command. With no arguments, run an inferior shell.