4

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?

okapi
  • 1,340
  • 9
  • 17

2 Answers2

11

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 ;-)

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • 1
    I can't understand how it works and where this piece of code should be used! – Sooora Dec 03 '20 at 20:02
  • That's actually a really good idea. Thanks!! – Alon Minski Jul 25 '21 at 12:45
  • @Sooora this code should go into the program You want to debug, right before the interesting code. It is an endless loop, which will make execution pause in the while-loop. Then You can attach the debugger to the process and, inside the debugger, You can set the "done" flag to 1 and the program will continue running inside Your debugger. – rob retro Aug 25 '22 at 13:51
0
using namespace std;
using namespace std::this_thread;
using namespace chrono;

void waitForDebugger()
{
    steady_clock::time_point tp1, tp2, tp3;
    microseconds d1 = microseconds(10000);
    microseconds d2 = microseconds(20000);

    bool looped = false;
    while (true)
    {
        sleep_for(d1);
        tp1 = steady_clock::now();
        if (looped && duration_cast<microseconds>(tp1 - tp3) > d2)
        {
            break;
        }
        sleep_for(d1);
        tp2 = steady_clock::now();
        if (looped && duration_cast<microseconds>(tp2 - tp1) > d2)
        {
            break;
        }
        sleep_for(d1);
        tp3 = steady_clock::now();
        if (looped && duration_cast<microseconds>(tp3 - tp2) > d2)
        {
            break;
        }

        looped = true;
    }
}
A.J.Bauer
  • 2,803
  • 1
  • 26
  • 35