We help IT Professionals succeed at work.

gdb to follow fork'd child processes

pzkhan asked
I am running a server that fork()'s off processes upon new connections in a loop. However, somewhere in the child section of the program there are errors.

I am trying to use gdb to find the problem, but having difficulty having gdb follow the child process. In particular, to do so, I set a break-point before the fork(). Before the fork executes, gdb returns me to the command prompt. I then enter "set fork-follow-mode" to follow a child process through. Once the child terminates, I would expect one of two things:
A) The parent process is executed from where it left off at the break
B) gdb returns me back to the command prompt, but this time to the parent process.

At the least, I would expect gdb to break once again when it reaches the fork() where the break was set.

Instead, the program executes as if the break was not there, and spawns several new child processes. Why is that? Shouldn't the parent stop at the break again?

Please assist.
Watch Question

evilrixSenior Software Engineer (Avast)

This is a purely speculative suggestion since I've never actually used gdb to do this, but...

...I wonder if a new instance of gdb has to be started every time it has to switch process context. If that is the case I suspect the break-points are actually being reset. Try checking to make sure the break-points you've set are still active once you've followed your fork to the child. If not I guess at least you'll know what's happening.

"On most systems, gdb has no special support for debugging programs which create additional processes using the fork function."

The above link describes a workaround; but I had just used printf (ugh) to complete the debugging.

BTW, using ddd gives you a nice GUI over gdb.
It sounds like gdb is following the fork to the child as it should.

Parent and child processes run asynchronously.  Both of your expectations suggest that the parent process is suspended while the child runs, and gdb can "pick up where it left off".  This doesn't happen.  When fork is executed, both parent and child processes are independent and both are running.  

In general, gdb only traces a single process at a time.  Take a look at "set detach-on-fork" in the reference phoffric gave.  Also http://sourceware.org/gdb/onlinedocs/gdb/Inferiors-and-Programs.html#Inferiors-and-Programs.  When gdb documentation talks about "inferiors" it means programs or processes being debugged.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.