How to attach to a child process in GDB and break at main()?
I want to debug the main() function in a child process of a multi-process application on a remote (embedded) machine.
In my particular case, there is no way to start the child process standalone (the parent has to start it). I now have this in my ~/.gdbinit
file (assume I want to break at main()
in the process for which the source code is at <path-to-my-cpp-file>
):
# contents of .gdbinit
cd /absolute/path/to/project
define target hookpost-remote
break <path-to-my-cpp-file>/main.cpp:main
set follow-fork-mode child
set detach-on-fork off
set solib-search-path /lib:/
Then, on the remote machine I do
gdbserver <if-address>:1234 path-to-my-parent-executable
And in GDB I get
No source file named <path-to-my-cpp-file>/main.cpp.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not
from terminal]
I can issue that break
command manually and answer yes. But it seems like something is wrong.
Then I do continue
and gdb gets stuck at Reading /lib/.debug/libm-2.28.so from remote target...
It's been over half an hour in this state with no further output, so I gave up.
What is the best way to achieve my goal of attaching to and debugging a child process?
I also tried the following to no avail:
In the child main.cpp file set something like:
#define DEBUG
#ifdef DEBUG
int i = 0;
while (i == 0)
{
usleep(100000); // sleep for 0.1 seconds
}
#endif // DEBUG
Build with no optimisations -O0
, then
Attach the gdbserver to the pid of the desired process with gdbserver -- attach <if-addess>:1234 <PID>
, then while in gdb do:
set my breakpoint where I want it
Then break out of the while loop by doing: set var i = 1
But this is what I get when doing this:
(gdb) bt
#0 0x00007fde0e247ff0 in nanosleep () from target:/lib/libc.so.6
#1 0x00007fde0e271c14 in usleep () from target:/lib/libc.so.6
#2 0x000055866cbbcad3 in main (argc=3, argv=0x7fff75b45148)
at <path-to-my-cpp-file>/main.cpp:196
(gdb) set var i=1
No symbol "i" in current context.
So since I am in nanosleep () there's no i
in this context.
So what if I step out of Nanosleep?
(gdb) n
Single stepping until exit from function nanosleep,
which has no line number information.
Program terminated with signal SIGKILL, Killed.
The program no longer exists.
How do people do this trick properly?
Thanks