kill 进程时遇到的一件有意思的事情

1.案例现象

一般来讲,我们在 kill 掉一个进程的时候通常有两个选择:

  1. 找到进程的 pid 号,然后执行 kill 命令
  2. 找到进程的名字,然后执行 pkill 命令

pkill 和 kill 命令都是向指定的进程发送信号,从而完成终结进程的操作,主要区别在于 pkill 命令与 pgrep 配套使用,能够踢出指定终端用户、同时根据 UID 和用户名来终止进程

今天给大家分享一件我在使用 pkill 命令时遇到的比较有意思的事情

这台机器上(Cent OS7)运行着一个进程 after_sleep60s_output

[root@localhost ~]# ps -ef | grep [a]fter
root      49146  48933  0 09:39 pts/0    00:00:00 /usr/local/bin/after_sleep60s_output

执行 pkill 命令

[root@localhost ~]# pkill after_sleep60s_output

然后当我使用 ps 命令查看的时候,我发现这个进程还在,而且返回了状态码 1

[root@localhost ~]# echo $?
1

用 kill 命令试试,发现成功了

[root@localhost ~]# kill 49146

奇怪?为什么用 pkill 命令 kill 不掉这个进程?

2.定位问题

通过 man pkill 我发现,pkill 命令是默认结合 pgrep 来使用的

pgrep 首先找出目标进程(running),然后 pkill 再根据 pgrep 的结果来 kill 目标进程

pgrep looks through the currently running processes and lists the process IDs which match the selection criteria to stdout. All the criteria have to match. For example,

​ $ pgrep -u root sshd

will only list the processes called sshd AND owned by root. On the other hand,

​ $ pgrep -u root,daemon

will list the processes owned by root OR daemon.

pkill will send the specified signal (by default SIGTERM) to each process instead of listing them on stdout.

pgrep 找目标进程是通过获取 /proc/[pid]/stat 文件中的进程名来实现的,但是这个文件中的进程名是有长度限制的——只有15个字符

Linux 中的每一个进程都维护了一个 struct_task_struct 结构体,这个结构体在/usr/src/kernels/内核版本/include/linux/sched.h里面

这里面有一个字段定义了不包括路径的可执行文件的名字,最大长度是 16 bytes,除去最后一个留给 null 的,就只有最多 15 个字符

/* Task command name length */
#define TASK_COMM_LEN 16
 char comm[TASK_COMM_LEN]; /* executable name excluding path
                              - access with [gs]et_task_comm (which lock
                                   it with task_lock())
                              - initialized normally by setup_new_exec */

然后我们看一下上面例子中进程对应的 stat 文件

[root@localhost ~]# cat /proc/49146/stat
49212 (after_sleep60s_) S 48933 49212 48933 3 .....

可以看到文件里面的进程名字被截断成了15个字符:after_sleep60s_

如果要使用 pkill 命令,正确方式如下:

[root@localhost ~]# pkill after_sleep60s_

你也可以加一个 -f 参数

[root@localhost ~]# pkill -f after_sleep60s_output

这个参数会告诉 pkill 不去/proc/[pid]/stat 文件找进程,而是去 /proc/[pid]/cmdline

里面找

这个文件里面包含了进程启动的时候的完整命令,包括参数

[root@localhost ~]# /proc/49146/cmdline
/usr/local/nginx/sbin/after_sleep60s_output

3.解决问题

想要准确的 kill 掉一个进程,可以使用下面的方法:

  • pidof 命令获取到进程对应的 PID,再使用 kill 命令
  • 使用 systemd 启动的,通过 systemctl 命令来控制
  • 使用 pkill 命令的时候建议加上 -f 参数

最后附上相关 issue 链接:

1、https://stackoverflow.com/questions/23534263/what-is-the-maximum-allowed-limit-on-the-length-of-a-process-name

猜你喜欢

转载自blog.csdn.net/s_alted/article/details/129988761
今日推荐