等待gdb附加 [英] wait for gdb to attach

查看:57
本文介绍了等待gdb附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常将gdb用于1或2个项目.IE.我调用 gdb --args prog args .gdb与我正在调试的程序在同一tty中运行.

I've been using gdb normally for 1 or 2 projects. I.e. I invoke gdb --args prog args . gdb runs in the same tty as the program I'm debugging.

但是,我最新的项目正在修改dtach实用程序.这是一个类似于screen的程序,因此tty的重定向到了其他地方,因此我必须使用gdb的附加功能.

However my latest project is modifying the dtach utility. This is a program like screen, so the tty's are redirected elsewhere, thus I have to use gdb's attach functionality.

gdb附加的问题是,显然您不能从一开始就附加,因为您首先需要运行该程序才能获取要附加的pid.

The problem with gdb attach is that obviously you can't attach from the very beginning as you need to run the program first in order to get a pid to attach to.

有什么办法可以让程序在某个时刻等待,直到附加了gdb吗?

Is there any way I can get a program to wait at a point until gdb is attached?

我在cygwin上无法使用gdbserver.我也尝试使用 pause(),但是当我尝试继续时,它只是挂了.

I can't use gdbserver as I'm on cygwin. Also I tried using pause(), but that just hung when I tried to continue.

推荐答案

这是我解决此问题的方法.我也看到其他人也这样做.

Here is how I solve this problem. I have seen other people do this trick as well.

选择一些您希望程序停止的位置,然后等待您附加调试器.对于大多数程序而言,这只是开始,但是如果有一些初始化工作需要执行,则可能需要先完成然后再执行.

Pick some place you want your program to stop and wait for you to attach the debugger. For most programs, this will be the very beginning, but if there is some init work you need to do you might want to finish that up and then do this.

放入与此类似的循环:

#ifdef DEBUG

int i = 0;

while (i == 0)
{
    usleep(100000);  // sleep for 0.1 seconds
}

#endif // DEBUG

成功附加到进程后,可以使用调试器更改变量 i 的值,这将打破循环并允许正常执行继续.

Once you have successfully attached to the process, you can use the debugger to change the value of the variable i, which will break the loop and allow normal execution to continue.

gdb命令将变量更改为1: set var i = 1

The gdb command to change the variable to 1: set var i = 1

我一直在做的另一件事:我定义了一个短函数,称为 nop(),它什么都不做(无操作").然后,我在要中断的任何地方坚持调用 nop(),并在 nop()内放置一个断点.

Another thing I do all the time: I define a short function called nop() that does nothing ("no operation"). Then I stick in a call to nop() anyplace I want to break, and put a breakpoint inside nop().

注意:如果使用 -O0 构建调试版本,则编译器不会优化该变量.如果您需要使用此技巧来优化构建,我想您需要将变量声明为 volatile .

Note: if you build your debug builds with -O0 then the compiler won't optimize away the variable. If you needed this trick to work with an optimized build, I guess you would need to declare the variable as volatile.

这篇关于等待gdb附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆