2010-02-22 176 views

回答

62

是的。使用attach命令。查看this link了解更多信息。在GDB控制台输入help attach给出如下:

(gdb) help attach 

附加到一个进程或GDB之外的文件。 此命令附加到另一个目标,它与您上次的 “target”命令相同(“info files”将显示您的目标堆栈)。 该命令可能会将进程ID,进程名称 (带有可选的进程ID作为后缀)或设备文件作为参数。 对于进程ID,您必须具有发送进程信号的权限, 并且它必须与调试器具有相同的有效uid。 在现有进程中使用“attach”时,调试器会查找正在运行的程序,首先查看当前工作的 目录,或者(如果未找到)使用源文件搜索路径 (请参阅“directory “命令)。您也可以使用“file”命令 来指定程序并加载其符号表。


注意:您可能会遇到困难连接到一个过程中,由于improved security in the Linux kernel - 例如连接到从另一个外壳的孩子。

根据您的要求,您可能需要设置/proc/sys/kernel/yama/ptrace_scope。现在许多系统默认为1或更高。

The sysctl settings (writable only with CAP_SYS_PTRACE) are: 

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other 
    process running under the same uid, as long as it is dumpable (i.e. 
    did not transition uids, start privileged, or have called 
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is 
    unchanged. 

1 - restricted ptrace: a process must have a predefined relationship 
    with the inferior it wants to call PTRACE_ATTACH on. By default, 
    this relationship is that of only its descendants when the above 
    classic criteria is also met. To change the relationship, an 
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare 
    an allowed debugger PID to call PTRACE_ATTACH on the inferior. 
    Using PTRACE_TRACEME is unchanged. 

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace 
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME. 

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via 
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed. 
+8

该链接已损坏:(从我的角度来看,我喜欢[J. Polfer](http:// stackoverflow)中的[This one](http://stackoverflow.com/a/2702170/938111) .com/users/40411/j-polfer)。干杯;) – olibre 2013-03-25 10:56:19

+0

我已修复链接。 – Attie 2017-10-13 10:06:41

+0

这是否也适用于远程目标上的进程的PID? – Bionix1441 2018-03-08 09:20:46

12

要使用的命令是gdb attach pid其中pid是要附加到进程的进程ID。

81

您可以使用gdb -p PID附加到正在运行的进程。

2

是的,你可以。假定进程foo正在运行...

 
ps -elf | grep foo 

look for the PID number 

gdb -a {PID number} 
+5

你在运行什么样的发行版?使用最新版本的Fedora,'gdb -a'会打印出一个“选项-a不明确”的错误。 – 2010-02-22 14:16:35

+1

官方的说法是-p/- pid – 2017-08-18 15:43:08

21

是的。你可以这样做:

gdb program_name program_pid 

快捷方式将(假设只有一个实例在运行):

gdb program_name `pidof program_name` 
+0

我不知道那是干什么的,但它确实是地狱不适合我。它说不存在。 – Owl 2016-02-27 19:37:17

+2

我发现这个效果最好,因为它除了附加到进程外还加载符号表。应该注意的是,如果你和二进制文件在同一个目录中,'program_name'就可以工作。我认为如果你在一个不同的目录中,这个二进制文件的路径可以工作。 – KarateSnowMachine 2016-05-18 17:49:58

2

PS -elf似乎并没有显示PID。 我建议使用来代替:

ps -ld | grep foo 
gdb -p PID 
1

如果一个人要附加一个过程,这个过程必须有相同的所有者。根可以附加到任何进程。

相关问题