39

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 Answers 4

30

(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.

Sign up to request clarification or add additional context in comments.

3 Comments

is there a way to use the output of the shell command in a gdb command without copying? attach shell ps -C <program_name> doesn't seem to work for me, so I can only do shell ps -C <program_name> <copy the output> attach <paste> but it would be great if there was a better option
in my case I need to shell to a ssh command to get the .text address of a kernel module so I can tell the local gdb to load symbols for that address, being able to take the result of a script and run it as a gdb command would make this super easy.
2021 and looking for the same. I'd be happy enough if I could display the output of a shell-command called in a "define".
24
gdb$ shell

shell$ execute_your_commands 

shell$ exit

gdb$ you_have_returned_back_to_gdb_prompt

Comments

16

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.

1 Comment

In this mode gdb does not seem to pick up or be able to report problems when there is core dump.
8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.