Debugging child processes on OS X with GDB

Hopefully, this will save folks some time who run into this.

What do you do if you want to debug a child process spawned by the parent process that gdb is attached to?

GDB’s documentation on forking would lead you to believe that this is as simple as:

set follow-fork-mode child 

That may be true on recent linux kernels (version 2.5.60 and later) but OS X doesn’t appear to have the kernel hooks to enable that. So what is a developer to do?

gdb ––wait exe

Assuming you knew nothing about the processes you were debugging (as I didn’t) but you had a hunch that it was spawning a child process (because none of the interesting breakpoints you set were hit), then you could grep through your code for a call to fork, vfork, or posix_spawn (posix_spawn was what I found and I’d bet its probably what you’ll find as well).

Assuming posix_spawn is what you’ve got, life is fairly easy (if its fork you’ll have different legwork to do) everything below assumes posix_spawn is in your code.

Set a breakpoint on the call to posix_spawn and run through the parent program to that point. Print out the path argument to posix_spawn as that is the executable that will be spawned.

Now to actually get debugging your child process.

  1. Restart your parent process with gdb attached
  2. Set GDB to break on main
  3. Run your parent process to the break point on main
  4. Fire up a new terminal window and run

    gdb ––wait child process’s name

  5. Now continue your parent process until the child is spawned by posix_spawn

This should cause the child process to spawn out of the parent and get picked up in the second instance of gdb. You can work with the child from there and as a benefit, you also have gdb attached to your parent process and can debug that as well.

  1. loarabia posted this