我可以使用GDBdebugging正在运行的进程吗?

在linux下,我可以使用GDB来debugging当前正在运行的进程吗?

是。 使用attach命令。 看看这个链接了解更多信息。 键入help attach在GDB控制台上提供以下内容:

 (gdb) help attach 

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


注意:由于Linux内核的安全性提高,您可能难以连接到某个进程,例如,将一个shell的孩子连接到另一个shell的孩子。

您可能需要根据您的要求设置/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 (ie 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. 

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

是。 你可以做:

 gdb program_name program_pid 

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

 gdb program_name `pidof program_name` 

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

是的你可以。 假设进程foo正在运行…

 ps -elf |  grep foo

查找PID号码

 gdb -a {PID号码}

ps -elf似乎不显示PID。 我build议使用:

 ps -ld | grep foo gdb -p PID 

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