3
votes

I'd like to attach gdb to a process where I can't easily control the startup of the process because it is run from inetd and where the process completes too fast to be able to attach to it once it starts.

What I'd like to do is insert a bit of code at the particular point that I want to start debugging. That code would ideally wait for the debugger to attach and then continue. I've tried with a sleep but it is then tricky to choose a delay long enough that I have time to catch it but short enough not to be a nuisance waiting for it to elapse after gdb is attached.

Is there any better choices of code to insert or to call for this purpose?

2
You can also set follow-fork-mode child to debug new child process. - ks1322

2 Answers

9
votes

What I'd like to do is insert a bit of code at the particular point that I want to start debugging.

I usually do it like this:

volatile int done = 0;
while (!done) sleep(1);

Attach GDB (you'll be inside sleep). Do finish, then set var done = 1, and enjoy the rest of your debugging session ;-)

0
votes

On linux if I want the program to wait until the debugger is attached I use a variation of the non invasive way @Employed Russian described.

Since I don't want to change a variables value every time but simply click "continue" in the IDE I use this:

static void waituntildebugerconnected() {
    cout << "set breakpoints on the two lines with 'usleep' and attach debugger" << std::endl;
    bool wait = true;
    timeval wt1, wt2;
    double welapsed;
    while (wait) {
        gettimeofday(&wt1, NULL);
        usleep(100000); // set breakpoint here
        gettimeofday(&wt2, NULL);
        welapsed = (wt2.tv_sec - wt1.tv_sec) * 1000.0;
        welapsed += (wt2.tv_usec - wt1.tv_usec) / 1000.0;
        wait = (welapsed < 110);
    }
    usleep(100000); // set breakpoint here
}