using gdb to debug a interactive program that reads input from stdin
Asked Answered
G

3

7

I'm writing a client/server program in C.

My client has a thread reading input from stdin, it's just a while(1) loop to read input from stdin. Whenever it reads a line, it deliver it to another thread that handles message parsing and framing.

As I enter gdb, the command line is occupied by gdb prompt and I can no longer input lines into stdin.

Is there a way to do it? (I don't want to redirect stdin to an input file because I've tried this method and it didn't work)

Gamin answered 3/2, 2017 at 1:14 Comment(0)
P
10

Run your program in one terminal and attach to it from gdb in another terminal.

To attach to a running program, find the process ID (PID) of the program you want to attach to, then execute gdb <executable> <PID>.

Personally answered 3/2, 2017 at 1:17 Comment(3)
how to attach a process to gdb?Gamin
What if I want to debug program startup?Albaalbacete
@Gamin that command will attach directly your process. It required root permission in my try.Aladdin
P
2

As an addition to Jonathan Reinhart's answer, here is a oneliner to attach to a running program by name:

gdb -p $(pgrep <executable-name>)
Paranymph answered 9/5, 2021 at 8:33 Comment(2)
This works if there is only one running instance of <executable-name>.Personally
One of these does the job: gdb -p $(pgrep <executable-name> | select); gdb -p $(pgrep <executable-name> | peco); gdb -p $(pgrep <executable-name> | fzf );Paranymph
G
1

As a clarification you don't need the executable name if you do know the process id of the program. This will allow you to attach a program directly.

gdb -p PID
Goggle answered 14/11, 2022 at 18:23 Comment(3)
This will work, but I don't think GDB will know where to find the executable in order to access the symbols and debug info.Personally
In principle if the executable is built with debug symbols or say RelWithDebInfo modern gdb is able to attach the executable corresponding to the PID specified.Goggle
Oh it probably uses /proc/$PID/exe.Personally

© 2022 - 2024 — McMap. All rights reserved.