在linux下,我可以使用GDB调试当前正在运行的进程吗?
是。使用attach命令。查看此链接以获取更多信息。打字help attach在GDB控制台提供了以下:
attach
help attach
(gdb) help attach 附加到GDB外部的进程或文件。该命令附加到另一个目标,该目标与上一个“ target”命令的类型相同(“ info files”将显示目标堆栈)。该命令可以将进程ID,进程名称(带有可选的进程ID作为后缀)或设备文件作为参数。对于进程ID,您必须具有向该进程发送信号的权限,并且该信号必须具有与调试器相同的有效uid。当attach对现有的进程使用“ ”时,调试器会查找该进程中正在运行的程序,首先在当前工作目录中查找,或者使用源文件搜索路径(如果在该目录中找不到)(请参阅“ directory“命令)。您也可以使用“ file”命令指定程序,并加载其符号表。
(gdb) help attach
附加到GDB外部的进程或文件。该命令附加到另一个目标,该目标与上一个“ target”命令的类型相同(“ info files”将显示目标堆栈)。该命令可以将进程ID,进程名称(带有可选的进程ID作为后缀)或设备文件作为参数。对于进程ID,您必须具有向该进程发送信号的权限,并且该信号必须具有与调试器相同的有效uid。当attach对现有的进程使用“ ”时,调试器会查找该进程中正在运行的程序,首先在当前工作目录中查找,或者使用源文件搜索路径(如果在该目录中找不到)(请参阅“ directory“命令)。您也可以使用“ file”命令指定程序,并加载其符号表。
target
info files
directory
file
注意:由于Linux内核中提高了安全性,因此可能难以附加到进程上,例如,从另一个shell附加到一个shell的子进程。
您可能需要/proc/sys/kernel/yama/ptrace_scope根据需要进行设置。现在,许多系统默认为1或更高。
/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.