Search code examples
gdb

Is there a way to tell process to wait for gdb to attach to it?


I have a question similar to Is there any way to tell GDB to wait for a process to start and attach to it?, but it goes the other way -- I'd like to have gdb attach to an already-running process, but have the process pause until gdb is finished attaching.

More specifically, the process itself would fork, and the child would exec gdb $program -p $parentpid -ex 'c', or something like that. The parent would wait for the gdb to attach before continuing. I'd like to avoid simply waiting an arbitrary amount of time before continuing, as I'd like to avoid any assumptions on how long it takes for gdb to startup.

I'm not sure if this is possible, but it would be very useful if it was.


Solution

  • The parent would wait for the gdb to attach before continuing.

    Assuming you are using Linux, the parent could repeatedly read /proc/self/status, waiting for TracerPid to become non-zero.

    However, that is somewhat pointless: when GDB attaches your process, GDB will stop it (i.e. the process will never actually see TracerPid != 0 until after GDB has attached and continued your attached process).

    So the solution in this answer will work just as well (although it does require GDB to do more than just continue your process).