设置coredump文件生成目录
使用gdb调试运行中的Python进程
步骤一:开启coredump文件生成
ulimit-cunlimited
步骤二:设置coredump文件位置
vi/etc/sysctl.conf
更改(添加)如下两个变量
kernel.core_pattern=/var/core/core_%e_%p
kernel.core_uses_pid=0
这儿是改为生成目录在/var/core/,%e代表程序名称linux查看dump文件linux设置默认网关,%p是进程ID
假如想直接生成在可执行文件相同目录,上面不要加任何目录linux查看dump文件,直接
kernel.core_pattern=core_%e_%p
步骤三:让更改生效
sysctl-p/etc/sysctl.conf
假定一个服务器上运行了下边这样的test.py程序linux是什么系统,我们如何能够晓得程序是否在正常运行,运行到哪一步了呢?
import time def do(x): time.sleep(10) def main(): for x in range(10000): do(x) if __name__ == '__main__': main()
这个程序既没有日志也没有print输出,通过查看日志文件/标准输出/标准错误是没有办法确认程序状况的。一种可行的办法就是使用gdb来查看程序当前的运行状况。
测试环境打算工作
安装gdb和python2.7-dbg:
$ sudo apt-get install gdb python2.7-dbg
设置/proc/sys/kernel/yama/ptrace_scope:
$ echo 0 |sudo tee /proc/sys/kernel/yama/ptrace_scope
运行test.py:
$ python test.py & [1] 6489
通过gdbpythonPID来调试运行中的进程:
$ gdb python 6489 GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 ... For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from python...Reading symbols from /usr/lib/debug/.build-id/90/d1300febaeb0a626baa2540d19df2416cd3361.debug...done. done. ... Reading symbols from /lib/ld-linux.so.2...Reading symbols from /usr/lib/debug//lib/i386-linux-gnu/ld-2.23.so...done. done. 0xb778fc31 in __kernel_vsyscall () (gdb)
生成corefile
为了不影响运行中的进程,可以通过生成corefile的形式来保存进程的当前信息:
(gdb) generate-core-file warning: target file /proc/6489/cmdline contained unexpected null characters Saved corefile core.6489 (gdb) quit A debugging session is active. Inferior 1 [process 6489] will be detached. Quit anyway? (y or n) y
可以通过gdbpythoncore.PID的方法来读取corefile:
$ gdb python core.6489 GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 ... Type "apropos word" to search for commands related to "word"... Reading symbols from python...Reading symbols from /usr/lib/debug/.build-id/90/d1300febaeb0a626baa2540d19df2416cd3361.debug...done. done. warning: core file may not match specified executable file. [New LWP 6489] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/i386-linux-gnu/libthread_db.so.1". Core was generated by `python'. #0 0xb778fc31 in __kernel_vsyscall () (gdb)
可用的python相关的命令
可以通过输入py之后加tab键的形式来查看可用的命令:
(gdb) py py-bt py-down py-locals py-up python-interactive py-bt-full py-list py-print python
可以通过helpcmd查看各个命令的说明:
(gdb) help py-bt Display the current python frame and all the frames within its call stack (if any)
当前执行位置的源码
(gdb) py-list 1 # -*- coding: utf-8 -*- 2 import time 3 4 5 def do(x): >6 time.sleep(10) 7 8 9 def main(): 10 for x in range(10000): 11 do(x) (gdb)
可以看见当前正在执行time.sleep(10)