用kill -6 pid 主动杀死进程, 使进程abort/coredump, 有哪些用处?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:44   2669   0

在实际开发中, 要灵活处理各种问题, 今天我们来说说kill -6 命令的使用, 它可以让主动让进程abort/coredump, 来看看一个例子:

#include <iostream>
#include <cmath>
using namespace std;

struct Point
{
 int x;
 int y;
};

int main() 
{
 Point po;
 po.x = 1;
 po.y = 2;
 float distance = sqrt(po.x * po.x + po.y * po.y);
 
 getchar();
 return 0;
}

很多时候, 我们需要知道变量的值, 但加log再编译, 又太慢了。 怎么办呢? 有的人说用单步调试, 其实我个人是不太喜欢用单步调试的, 除非迫不得已。 我们来看看, 用主动core来看变量的值。 还能这样用啊!

请确保:

1. 你的机器开启了core开关, 用ulimit -c 检查一下吧, 我们说过很多次了)

2. 编译的时候用-g选项

来看看, 先编译运行:

xxxxxx $ g++ test.cpp -g && ./a.out

然后在另外一个窗口执行如下命令, 让进程abort/coredump:

xxxxxx $ ps -aux | grep a.out | awk '{print $2}' | xargs kill -6

然后分析core文件:

xxxxxx $ gdb a.out core 
GNU gdb 6.6
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i586-suse-linux"...
Using host libthread_db library "/lib/libthread_db.so.1".

warning: Can't read pathname for load map: Input/output error.
Reading symbols from /lib/libonion.so...done.
Loaded symbols for /lib/libonion.so
Reading symbols from /usr/lib/libstdc++.so.6...done.
Loaded symbols for /usr/lib/libstdc++.so.6
Reading symbols from /lib/libm.so.6...done.
Loaded symbols for /lib/libm.so.6
Reading symbols from /lib/libgcc_s.so.1...done.
Loaded symbols for /lib/libgcc_s.so.1
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/libdl.so.2...done.
Loaded symbols for /lib/libdl.so.2
Reading symbols from /lib/libpthread.so.0...done.
Loaded symbols for /lib/libpthread.so.0
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./a.out'.
Program terminated with signal 6, Aborted.
#0  0xb7d91b0e in __read_nocancel () from /lib/libc.so.6
(gdb) bt
#0  0xb7d91b0e in __read_nocancel () from /lib/libc.so.6
#1  0xb7d410d8 in _IO_file_read_internal () from /lib/libc.so.6
#2  0xb7d4235b in _IO_new_file_underflow () from /lib/libc.so.6
#3  0xb7d42a9b in _IO_default_uflow_internal () from /lib/libc.so.6
#4  0xb7d43ddd in __uflow () from /lib/libc.so.6
#5  0xb7d3debe in getchar () from /lib/libc.so.6
#6  0x0804867c in main () at test.cpp:18
(gdb) f 6
#6  0x0804867c in main () at test.cpp:18
18              getchar();
(gdb) i locals
po = {x = 1, y = 2}
distance = 2.23606801
(gdb) 

然后就知道答案了, 顺便还能熟悉下gdb调试core.



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP