View Full Version : GDB attach to a running process

Oct 6, 2010, 08:00 PM
I'm studying system-level programming. I have a little program that uses fork() to create a new child process. I set a breakpoint after the creation of the child process using GDB. Then, I ran it (through GDB).

With a new terminal window I check the processes id's using "ps -l -u my_username".
With another terminal window I enter GDB, and enter the command "attach child_pid". Still, no problem. I set a breakpoint. But then, when I do "n" inside that GDB session, in order to run/debug the child process,I keep getting the error :"Cannot find bounds of current function".

When I check again the processes PID's I notice that the child PPID changed to a different value than the Parent's original PID. I don't know if that's the problem.

Hope someone can help me. I'm new at this, but I definitely want to learn more, and use MAC OS to do it.

Oct 7, 2010, 04:51 PM
This works for me. (Mac OS X 10.6.4, gcc 4.2.1, gdb 6.3.50-20050815.)

#include <stdio.h>
#include <unistd.h>

pid_t pid = fork();

if (pid == (pid_t)0)
volatile int flag = 0; // use gdb to set non-zero to exit the loop
unsigned counter = 0;
while (!flag)
printf("child %u\n", counter);
printf("child exit\n");
printf("parent exit (child pid %d)\n", pid);

return 0;


$ gcc -g fork.c
$ gdb a.out
(gdb) b fork.c:23
(gdb) r

And, in a second terminal window (where PID was printed by fork.c or found from ps)

$ gdb a.out PID
(gdb) b fork.c:17
(gdb) c

If the child exits then the child gdb session gets confused...

(gdb) set flag=1
(gdb) c
^CInterrupted while waiting for the program.
Give up (and stop debugging it)? (y or n)

...but otherwise this works. Hope it helps :)

Oct 8, 2010, 07:12 PM
Thank you very much for your help!My (Windows/Ubuntu users) colleagues were messing around with me, saying that after all I couldn't make this course's project in MAC OSX =P. I'm glad that is all this features are working now, because debugging multiple processes can be needed!

I guess I can't set a breakpoint in the "while(!flag)" to make the command "continue" work, do you know why? thanks again!