Using gdb/ddd to debug child processes
If you have tried to debug a child process using ddd, you may have noticed
that ddd steps into the parent (and not the child) after the call to fork().
It is possible to debug the child as well, but it requires a special procedure.
Since the child is a seperate process, it will require a second debugger
window, and we will make use of gdb's ability to "attach" to a process
which is already running.
Before you start, you must do the following:
Now you are ready to start:
Make sure your call to fork() assigns a value to some variable
so you can read it easily, e.g. "pid = fork()".
Make sure you place a sleep() statement in the child as the first
line of code after the fork(), e.g. "sleep(60)"
[make the sleep() long enough for step 4 below ...]. The sleep()
statment can be removed once debugging is complete.
Compile your program with the "-g" option set, e.g. gcc myProg.c
-o myProg -g
Start 2 copies of ddd in the background, like "ddd myProg & ddd
myProg &". It is important that the two copies being running concurrently.
Pick (arbitrarily) one window to be the "parent" and set a breakpoint after
the call to fork() (but not in any code the
child will be executing ... that is, set the breakpoint somewhere in the
parent's code ... if you set the breakpoint in the child's code, DDD
will kill the child as soon as it is created!).
Run the parent to the breakpoint. Note the value returned by fork(),
i.e. the process ID of the child.
In the "child" window, type "attach <pid>" in the gdb console
window where <pid> is the child's process ID. Note: the gdb
console is found at the bottom of the ddd window; this is where you can
type commands directly to gdb.
Set a breakpoint in the child after the sleep() statement, and
click on "cont" (in the popup "Command Tool" window) to allow
the child to continue execution to the breakpoint.