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

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

nohup myprogram.sh &

nohup 会返回运行进程的 PID。接下来我会更多地谈论 PID。

管理正在运行的进程

每个进程都有一个唯一的进程标识号 (PID) 。这个数字是我们用来管理每个进程的。我们还可以使用进程名称,我将在下面演示。有几个命令可以检查正在运行的进程的状态。让我们快速看看这些命令。

PS

最常见的是 ps 命令。 ps 的默认输出是当前终端中运行的进程的简单列表。如下所示,第一列包含 PID。

alan@workstation:~$ ps
PID TTY   TIME CMD
23989 pts/0 00:00:00 bash
24148 pts/0 00:00:00 ps

我想看看我之前启动的 Nginx 进程。为此,我告诉 ps 给我展示每一个正在运行的进程( -e )和完整的列表( -f )。

alan@workstation:~$ ps -ef
UID  PID PPID C STIME TTY   TIME CMD
root   1  0 0 Aug18 ?  00:00:10 /sbin/init splash
root   2  0 0 Aug18 ?  00:00:00 [kthreadd]
root   4  2 0 Aug18 ?  00:00:00 [kworker/0:0H]
root   6  2 0 Aug18 ?  00:00:00 [mm_percpu_wq]
root   7  2 0 Aug18 ?  00:00:00 [ksoftirqd/0]
root   8  2 0 Aug18 ?  00:00:20 [rcu_sched]
root   9  2 0 Aug18 ?  00:00:00 [rcu_bh]
root  10  2 0 Aug18 ?  00:00:00 [migration/0]
root  11  2 0 Aug18 ?  00:00:00 [watchdog/0]
root  12  2 0 Aug18 ?  00:00:00 [cpuhp/0]
root  13  2 0 Aug18 ?  00:00:00 [cpuhp/1]
root  14  2 0 Aug18 ?  00:00:00 [watchdog/1]
root  15  2 0 Aug18 ?  00:00:00 [migration/1]
root  16  2 0 Aug18 ?  00:00:00 [ksoftirqd/1]
alan  20506 20496 0 10:39 pts/0 00:00:00 bash
alan  20520 1454 0 10:39 ?  00:00:00 nginx: master process nginx
alan  20521 20520 0 10:39 ?  00:00:00 nginx: worker process
alan  20526 20506 0 10:39 pts/0 00:00:00 man ps
alan  20536 20526 0 10:39 pts/0 00:00:00 pager
alan  20564 20496 0 10:40 pts/1 00:00:00 bash

您可以在上面 ps 命令的输出中看到 Nginx 进程。这个命令显示了将近 300 行,但是我在这个例子中缩短了它。可以想象,试图处理 300 行过程信息有点混乱。我们可以将这个输出输送到 grep ,过滤一下仅显示 nginx。

alan@workstation:~$ ps -ef |grep nginx
alan  20520 1454 0 10:39 ?  00:00:00 nginx: master process nginx
alan  20521 20520 0 10:39 ?  00:00:00 nginx: worker process

确实更好了。我们可以很快看到,Nginx 有 20520 和 20521 的 PID。

PGREP

pgrep 命令更加简化单独调用 grep 遇到的问题。

alan@workstation:~$ pgrep nginx
20520
20521

假设您在一个托管环境中,多个用户正在运行几个不同的 Nginx 实例。您可以使用 -u 选项将其他人排除在输出之外。

alan@workstation:~$ pgrep -u alan nginx
20520
20521

PIDOF

另一个好用的是 pidof 。此命令将检查特定二进制文件的 PID,即使另一个同名进程正在运行。为了建立一个例子,我将我的 Nginx 复制到第二个目录,并以相应的路径前缀启动。在现实生活中,这个实例可能位于不同的位置,例如由不同用户拥有的目录。如果我运行两个 Nginx 实例,则 pidof 输出显示它们的所有进程。