Linux中有效地管理进程的8个命令

2019-10-09 16:04:13王振洲

alan@workstation:~$ ps -ef |grep nginx
alan  20881 1454 0 11:18 ?  00:00:00 nginx: master process ./nginx -p /home/alan/web/prod/nginxsec
alan  20882 20881 0 11:18 ?  00:00:00 nginx: worker process
alan  20895 1454 0 11:19 ?  00:00:00 nginx: master process nginx
alan  20896 20895 0 11:19 ?  00:00:00 nginx: worker process

使用 grep 或 pgrep 将显示 PID 数字,但我们可能无法辨别哪个实例是哪个。

alan@workstation:~$ pgrep nginx
20881
20882
20895
20896

pidof 命令可用于确定每个特定 Nginx 实例的 PID。

alan@workstation:~$ pidof /home/alan/web/prod/nginxsec/sbin/nginx
20882 20881

alan@workstation:~$ pidof /home/alan/web/prod/nginx/sbin/nginx
20896 20895

TOP

top 命令已经有很久的历史了,对于查看运行进程的细节和快速识别内存消耗等问题是非常有用的。其默认视图如下所示。

top - 11:56:28 up 1 day, 13:37, 1 user, load average: 0.09, 0.04, 0.03
Tasks: 292 total, 3 running, 225 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.1 us, 0.2 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 16387132 total, 10854648 free, 1859036 used, 3673448 buff/cache
KiB Swap:  0 total,  0 free,  0 used. 14176540 avail Mem

 PID USER  PR NI VIRT RES SHR S %CPU %MEM  TIME+ COMMAND
17270 alan  20 0 3930764 247288 98992 R 0.7 1.5 5:58.22 gnome-shell
20496 alan  20 0 816144 45416 29844 S 0.5 0.3 0:22.16 gnome-terminal-
21110 alan  20 0 41940 3988 3188 R 0.1 0.0 0:00.17 top
 1 root  20 0 225564 9416 6768 S 0.0 0.1 0:10.72 systemd
 2 root  20 0  0  0  0 S 0.0 0.0 0:00.01 kthreadd
 4 root  0 -20  0  0  0 I 0.0 0.0 0:00.00 kworker/0:0H
 6 root  0 -20  0  0  0 I 0.0 0.0 0:00.00 mm_percpu_wq
 7 root  20 0  0  0  0 S 0.0 0.0 0:00.08 ksoftirqd/0

可以通过键入字母 s 和您喜欢的更新秒数来更改更新间隔。为了更容易监控我们的示例 Nginx 进程,我们可以使用 -p 选项并传递 PID 来调用 top 。这个输出要干净得多。

alan@workstation:~$ top -p20881 -p20882 -p20895 -p20896

Tasks: 4 total, 0 running, 4 sleeping, 0 stopped, 0 zombie
%Cpu(s): 2.8 us, 1.3 sy, 0.0 ni, 95.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 16387132 total, 10856008 free, 1857648 used, 3673476 buff/cache
KiB Swap:  0 total,  0 free,  0 used. 14177928 avail Mem

 PID USER  PR NI VIRT RES SHR S %CPU %MEM  TIME+ COMMAND
20881 alan  20 0 12016 348  0 S 0.0 0.0 0:00.00 nginx
20882 alan  20 0 12460 1644 932 S 0.0 0.0 0:00.00 nginx
20895 alan  20 0 12016 352  0 S 0.0 0.0 0:00.00 nginx
20896 alan  20 0 12460 1628 912 S 0.0 0.0 0:00.00 nginx

在管理进程,特别是终止进程时,正确确定 PID 是非常重要。此外,如果以这种方式使用 top ,每当这些进程中的一个停止或一个新进程开始时, top 都需要被告知有新的进程。

终止进程

KILL

有趣的是,没有 stop 命令。在 Linux 中,有 kill 命令。 kill 用于向进程发送信号。最常用的信号是“终止”( SIGTERM )或“杀死”( SIGKILL )。然而,还有更多。下面是一些例子。完整的列表可以用 kill -L 显示。