Linux Admin 简明教程

Linux Admin - Process Management

以下是与进程管理一起使用的常用命令:bg、fg、nohup、ps、pstree、top、kill、killall、free、uptime、nice。

Following are the common commands used with Process Management–bg, fg, nohup, ps, pstree, top, kill, killall, free, uptime, nice.

Work with Processes

Quick Note − Process PID in Linux

Quick Note − Process PID in Linux

在 Linux 中,每个正在运行的进程都被赋予一个 PID 或进程 ID 号码。这个 PID 就是 CentOS 识别特定进程的方式。正如我们所讨论的,systemd 是第一个启动的进程并在 CentOS 中被赋予 PID 1。

In Linux every running process is given a PID or Process ID Number. This PID is how CentOS identifies a particular process. As we have discussed, systemd is the first process started and given a PID of 1 in CentOS.

Pgrep 用于获取给定进程名称的 Linux PID。

Pgrep is used to get Linux PID for a given process name.

[root@CentOS]# pgrep systemd
1
[root@CentOS]#

如你所见,pgrep 命令返回了 systemd 的当前 PID。

As seen, the pgrep command returns the current PID of systemd.

Basic CentOS Process and Job Management in CentOS

在 Linux 中处理进程时,了解如何在命令行中执行基本的前台和后台进程非常重要。

When working with processes in Linux it is important to know how basic foregrounding and backgrounding processes is performed at the command line.

  1. fg − Bringsthe process to the foreground

  2. bg − Movesthe process to the background

  3. jobs − List of the current processes attached to the shell

  4. ctrl+z − Control + z key combination to sleep the current process

  5. & − Startsthe process in the background

让我们开始使用 shell 命令 sleep。 sleep 只会做它所命名的工作,在定义的时间段内 sleep。

Let’s start using the shell command sleep. sleep will simply do as it is named, sleep for a defined period of time − sleep.

[root@CentOS ~]$ jobs

[root@CentOS ~]$ sleep 10 &
[1] 12454

[root@CentOS ~]$ sleep 20 &
[2] 12479

[root@CentOS ~]$ jobs
[1]-  Running                 sleep 10 &
[2]+  Running                 sleep 20 &

[cnetos@CentOS ~]$

现在,我们将第一个作业置于前台 −

Now, let’s bring the first job to the foreground −

[root@CentOS ~]$ fg 1
sleep 10

如果你有留意,你便会注意到前台作业卡在你的 shell 中了。现在,我们将进程设为休眠,然后在后台重新启用它。

If you are following along, you’ll notice the foreground job is stuck in your shell. Now, let’s put the process to sleep, then re-enable it in the background.

  1. Hit control+z

  2. Type: bg 1, sending the first job into the background and starting it.

[root@CentOS ~]$ fg 1
sleep 20
^Z
[1]+  Stopped                 sleep 20

[root@CentOS ~]$ bg 1
[1]+ sleep 20 &

[root@CentOS ~]$

nohup

在从 shell 或终端进行操作时,值得注意的是,默认情况下,当 shell 关闭或用户注销时,附加至 shell 的所有进程和作业都会终止。在使用 nohup 时,如果用户注销或关闭附加该进程的 shell,进程将继续运行。

When working from a shell or terminal, it is worth noting that by default all the processes and jobs attached to the shell will terminate when the shell is closed or the user logs out. When using nohup the process will continue to run if the user logs out or closes the shell to which the process is attached.

[root@CentOS]# nohup ping www.google.com &
[1] 27299
nohup: ignoring input and appending output to ‘nohup.out’

[root@CentOS]# pgrep ping
27299

[root@CentOS]# kill -KILL `pgrep ping`
[1]+  Killed                  nohup ping www.google.com

[root@CentOS rdc]# cat nohup.out
PING www.google.com (216.58.193.68) 56(84) bytes of data.
64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 1 ttl = 128
time = 51.6 ms
64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 2 ttl = 128
time = 54.2 ms
64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 3 ttl = 128
time = 52.7 ms

ps Command

ps 命令通常由管理员使用,以调查特定进程的快照。ps 通常与 grep 配合使用,以筛选出特定进程进行分析。

The ps command is commonly used by administrators to investigate snapshots of a specific process. ps is commonly used with grep to filter out a specific process to analyze.

[root@CentOS ~]$ ps axw | grep python
762   ?        Ssl    0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork -nopid
1296  ?        Ssl    0:00 /usr/bin/python -Es /usr/sbin/tuned -l -P
15550 pts/0    S+     0:00 grep --color=auto python

在上方的命令中,我们看到了所有使用 Python 解释器的进程。结果中还包含我们的 grep 命令,它查找字符串 python。

In the above command, we see all the processes using the python interpreter. Also included with the results were our grep command, looking for the string python.

以下是与 ps 配合使用时最常见的命令行开关。

Following are the most common command line switches used with ps.

Switch

Action

a

Excludes constraints of only the reporting processes for the current user

x

Shows processes not attached to a tty or shell

w

Formats wide output display of the output

e

Shows environment after the command

-e

Selects all processes

-o

User-defined formatted output

-u

Shows all processes by a specific user

-C

Shows all processes by name or process id

--sort

Sorts the processes by definition

查看 nobody 用户正在使用的所有进程

To see all processes in use by the nobody user −

[root@CentOS ~]$ ps -u nobody
PID TTY          TIME CMD
1853 ?        00:00:00 dnsmasq

[root@CentOS ~]$

查看 firewalld 进程的所有信息

To see all information about the firewalld process −

[root@CentOS ~]$ ps -wl -C firewalld
F   S   UID   PID   PPID   C   PRI   NI   ADDR   SZ   WCHAN   TTY   TIME      CMD
0   S     0   762      1   0    80   0     -   81786  poll_s   ?   00:00:01 firewalld

[root@CentOS ~]$

让我们看看哪些进程消耗的内存最多

Let’s see which processes are consuming the most memory −

[root@CentOS ~]$ ps aux  --sort=-pmem | head -10
USER       PID   %CPU   %MEM   VSZ     RSS   TTY   STAT   START   TIME   COMMAND
cnetos     6130   0.7   5.7   1344512 108364  ?      Sl   02:16   0:29  /usr/bin/gnome-shell
cnetos     6449   0.0   3.4   1375872 64440   ?      Sl   02:16   0:00  /usr/libexec/evolution-calendar-factory
root       5404   0.6   2.1   190256  39920 tty1     Ssl+ 02:15   0:27  /usr/bin/Xorg :0 -background none -noreset -audit 4 -verbose -auth /run/gdm/auth-for-gdm-iDefCt/database -seat seat0 -nolisten tcp vt1
cnetos     6296   0.0   1.7   1081944 32136   ?      Sl   02:16   0:00  /usr/libexec/evolution/3.12/evolution-alarm-notify
cnetos     6350   0.0   1.5   560728  29844   ?      Sl   02:16   0:01  /usr/bin/prlsga
cnetos     6158   0.0   1.4   1026956 28004   ?      Sl   02:16   0:00  /usr/libexec/gnome-shell-calendar-server
cnetos     6169   0.0   1.4   1120028 27576   ?      Sl   02:16   0:00  /usr/libexec/evolution-source-registry
root       762    0.0   1.4   327144  26724   ?      Ssl  02:09   0:01  /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
cnetos     6026   0.0  1.4 1090832 26376      ?      Sl   02:16   0:00  /usr/libexec/gnome-settings-daemon

[root@CentOS ~]$

查看用户 centos 的所有进程,并格式化,显示自定义输出

See all the processes by user centos and format, displaying the custom output −

[cnetos@CentOS ~]$ ps -u cnetos -o pid,uname,comm
   PID    USER     COMMAND
   5802  centos   gnome-keyring-d
   5812  cnetos   gnome-session
   5819  cnetos   dbus-launch
   5820  cnetos   dbus-daemon
   5888  cnetos   gvfsd
   5893  cnetos   gvfsd-fuse
   5980  cnetos   ssh-agent
   5996  cnetos   at-spi-bus-laun

pstree Command

pstree 与 ps 类似,但并不常用。它以更清晰的树状模式显示进程。

pstree is similar to ps but is not often used. It displays the processes in a neater tree fashion.

[centos@CentOS ~]$ pstree
  systemd─┬─ModemManager───2*[{ModemManager}]
          ├─NetworkManager─┬─dhclient
          │                └─2*[{NetworkManager}]
          ├─2*[abrt-watch-log]
          ├─abrtd
          ├─accounts-daemon───2*[{accounts-daemon}]
          ├─alsactl
          ├─at-spi-bus-laun─┬─dbus-daemon───{dbus-daemon}
          │                 └─3*[{at-spi-bus-laun}]
          ├─at-spi2-registr───2*[{at-spi2-registr}]
          ├─atd
          ├─auditd─┬─audispd─┬─sedispatch
          │        │         └─{audispd}
          │        └─{auditd}
          ├─avahi-daemon───avahi-daemon
          ├─caribou───2*[{caribou}]
          ├─cgrulesengd
          ├─chronyd
          ├─colord───2*[{colord}]
          ├─crond
          ├─cupsd

pstree 的总输出可能超过 100 行。通常,ps 将提供更有用的信息。

The total output from pstree can exceed 100 lines. Usually, ps will give more useful information.

top Command

在解决 Linux 性能问题时, top 是最常用的命令之一。它适用于 Linux 中的实时统计和进程监控。以下是从命令行中调出时 top 的默认输出。

top is one of the most often used commands when troubleshooting performance issues in Linux. It is useful for real-time stats and process monitoring in Linux. Following is the default output of top when brought up from the command line.

Tasks: 170 total,   1 running, 169 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.3 us,  2.0 sy,  0.0 ni, 95.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1879668 total,   177020 free,   607544 used,  1095104 buff/cache
KiB Swap:  3145724 total,  3145428 free,      296 used.  1034648 avail Mem

PID    USER     PR   NI    VIRT     RES   SHR    S  %CPU  %MEM   TIME+   COMMAND
5404   root     20   0    197832   48024  6744   S   1.3   2.6  1:13.22   Xorg
8013   centos   20   0    555316   23104  13140  S   1.0   1.2  0:14.89   gnome-terminal-
6339   centos   20   0    332336   6016   3248   S   0.3   0.3  0:23.71   prlcc
6351   centos   20   0    21044    1532   1292   S   0.3   0.1  0:02.66   prlshprof

在运行 top 时用到的常用热键(在 shell 中运行 top 时,按相应键即可访问热键)。

Common hot keys used while running top (hot keys are accessed by pressing the key as top is running in your shell).

Command

Action

b

Enables / disables bold highlighting on top menu

z

Cycles the color scheme

l

Cycles the load average heading

m

Cycles the memory average heading

t

Task information heading

h

Help menu

Shift+F

Customizes sorting and display fields

以下是 top 中的常用命令行开关。

Following are the common command line switches for top.

Command

Action

-o

Sorts by column (can prepend with - or + to sort ascending or descending)

-u

Shows only processes from a specified user

-d

Updates the delay time of top

-O

Returns a list of columns which top can apply sorting

top 中的排序选项屏幕,使用 Shift+F 呈现。此屏幕允许在 top 中对显示和排序选项进行自定义。

Sorting options screen in top, presented using Shift+F. This screen allows customization of top display and sort options.

Fields Management for window 1:Def, whose current sort field is %MEM
Navigate with Up/Dn, Right selects for move then <Enter> or Left commits,
 'd' or <Space> toggles display, 's' sets sort.  Use 'q' or <Esc> to end!

* PID     = Process Id             TGID    = Thread Group Id
* USER    = Effective User Name    ENVIRON = Environment vars
* PR      = Priority               vMj     = Major Faults delta
* NI      = Nice Value             vMn     = Minor Faults delta
* VIRT    = Virtual Image (KiB)    USED    = Res+Swap Size (KiB)
* RES     = Resident Size (KiB)    nsIPC   = IPC namespace Inode
* SHR     = Shared Memory (KiB)    nsMNT   = MNT namespace Inode
* S       = Process Status         nsNET   = NET namespace Inode
* %CPU    = CPU Usage              nsPID   = PID namespace Inode
* %MEM    = Memory Usage (RES)     nsUSER  = USER namespace Inode
* TIME+   = CPU Time, hundredths   nsUTS   = UTS namespace Inode
* COMMAND = Command Name/Line
PPID    = Parent Process pid
UID     = Effective User Id

top,显示用户 rdc 的进程,并按内存使用量排序 −

top, showing the processes for user rdc and sorted by memory usage −

 PID   USER  %MEM  PR  NI    VIRT    RES    SHR    S %CPU     TIME+    COMMAND
 6130  rdc    6.2  20   0  1349592  117160  33232  S  0.0   1:09.34    gnome-shell
 6449  rdc    3.4  20   0  1375872   64428  21400  S  0.0   0:00.43    evolution-calen
 6296  rdc    1.7  20   0  1081944   32140  22596  S  0.0   0:00.40    evolution-alarm
 6350  rdc    1.6  20   0   560728   29844   4256  S  0.0   0:10.16    prlsga
 6281  rdc    1.5  20   0  1027176   28808  17680  S  0.0   0:00.78    nautilus
 6158  rdc    1.5  20   0  1026956   28004  19072  S  0.0   0:00.20    gnome-shell-cal

显示有效的 top 字段(概览) −

Showing valid top fields (condensed) −

[centos@CentOS ~]$ top -O
PID
PPID
UID
USER
RUID
RUSER
SUID
SUSER
GID
GROUP
PGRP
TTY
TPGID

kill Command

kill 命令用于通过其 PID 从命令 shell 终止进程。终止进程时,我们需要指定要发送的信号。信号让内核了解我们希望如何结束进程。最常用的信号是 −

The kill command is used to kill a process from the command shell via its PID. When killing a process, we need to specify a signal to send. The signal lets the kernel know how we want to end the process. The most commonly used signals are −

  1. SIGTERM is implied as the kernel lets a process know it should stop soon as it is safe to do so. SIGTERM gives the process an opportunity to exit gracefully and perform safe exit operations.

  2. SIGHUP most daemons will restart when sent SIGHUP. This is often used on the processes when changes have been made to a configuration file.

  3. SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The kernel needs an option to end a process that will not comply with requests. When a process is hung, the SIGKILL option is used to shut the process down explicitly.

对于可以使用 kill 发送的所有信号列表,可以使用 -l 选项 −

For a list off all signals that can be sent with kill the -l option can be used −

[root@CentOS]# kill -l
1) SIGHUP           2) SIGINT         3) SIGQUIT        4) SIGILL         5) SIGTRAP
6) SIGABRT          7) SIGBUS         8) SIGFPE         9) SIGKILL       10) SIGUSR1
11) SIGSEGV        12) SIGUSR2       13) SIGPIPE       14) SIGALRM       15) SIGTERM
16) SIGSTKFLT      17) SIGCHLD       18) SIGCONT       19) SIGSTOP       20) SIGTSTP
21) SIGTTIN        22) SIGTTOU       23) SIGURG        24) SIGXCPU       25) SIGXFSZ
26) SIGVTALRM      27) SIGPROF       28) SIGWINCH      29) SIGIO         30) SIGPWR
31) SIGSYS         34) SIGRTMIN      35) SIGRTMIN+1    36) SIGRTMIN+2    37) SIGRTMIN+3
38) SIGRTMIN+4     39) SIGRTMIN+5    40) SIGRTMIN+6    41) SIGRTMIN+7    42) SIGRTMIN+8
43) SIGRTMIN+9     44) SIGRTMIN+10   45) SIGRTMIN+11   46) SIGRTMIN+12   47) SIGRTMIN+13
48) SIGRTMIN+14    49) SIGRTMIN+15   50) SIGRTMAX-14   51) SIGRTMAX-13   52) SIGRTMAX-12
53) SIGRTMAX-11    54) SIGRTMAX-10   55) SIGRTMAX-9    56) SIGRTMAX-8    57) SIGRTMAX-7
58) SIGRTMAX-6     59) SIGRTMAX-5    60) SIGRTMAX-4    61) SIGRTMAX-3    62) SIGRTMAX-2
63) SIGRTMAX-1     64) SIGRTMAX

[root@CentOS rdc]#

使用 SIGHUP 来重启系统。

Using SIGHUP to restart system.

[root@CentOS]# pgrep systemd
1
464
500
643
15071

[root@CentOS]# kill -HUP 1

[root@CentOS]# pgrep systemd
1
464
500
643
15196
15197
15198

[root@CentOS]#

pkill 允许管理员按进程名称发送 kill 信号。

pkill will allow the administrator to send a kill signal by the process name.

[root@CentOS]# pgrep ping
19450
[root@CentOS]# pkill -9 ping
[root@CentOS]# pgrep ping
[root@CentOS]#

killall 将终止所有进程。小心以 root 身份使用 killall,因为它会终止所有用户的进程。

killall will kill all the processes. Be careful using killall as root, as it will kill all the processes for all users.

[root@CentOS]# killall chrome

free Command

free 是一个非常简单的命令,通常用于快速查看系统的内存。它显示已使用的物理内存和交换内存的总量。

free is a pretty simple command often used to quickly check the memory of a system. It displays the total amount of used physical and swap memory.

[root@CentOS]# free
             total       used      free      shared      buff/cache      available
Mem:        1879668     526284    699796     10304        653588          1141412
Swap:       3145724          0    3145724

[root@CentOS]#

nice Command

nice 允许管理员根据 CPU 使用情况设置进程的调度优先级。基本上,niceness 是内核将如何为进程或作业调度 CPU 时间片的。默认情况下,假定进程对 CPU 资源的访问权相同。

nice will allow an administrator to set the scheduling priority of a process in terms of CPU usages. The niceness is basically how the kernel will schedule CPU time slices for a process or job. By default, it is assumed the process is given equal access to CPU resources.

首先,让我们使用 top 查看当前正在运行的进程的优先级。

First, let’s use top to check the niceness of the currently running processes.

PID   USER   PR   NI    VIRT    RES    SHR   S  %CPU  %MEM     TIME+    COMMAND
28    root   39   19       0      0      0   S  0.0   0.0    0:00.17    khugepaged
690   root   39   19   16808   1396   1164   S  0.0   0.1    0:00.01    alsactl]
9598  rdc    39   19  980596  21904  10284   S  0.0   1.2    0:00.27    tracker-extract
9599  rdc    39   19  469876   9608   6980   S  0.0   0.5    0:00.04    tracker-miner-a
9609  rdc    39   19  636528  13172   8044   S  0.0   0.7    0:00.12    tracker-miner-f
9611  rdc    39   19  469620   8984   6496   S  0.0   0.5    0:00.02    tracker-miner-u
27    root   25    5       0      0      0   S  0.0   0.0    0:00.00    ksmd
637   rtkit  21    1  164648   1276   1068   S  0.0   0.1    0:00.11    rtkit-daemon
1     root   20    0  128096   6712   3964   S  0.3   0.4    0:03.57    systemd
2     root   20    0       0      0      0   S  0.0   0.0    0:00.01    kthreadd
3     root   20    0       0      0      0   S  0.0   0.0    0:00.50    ksoftirqd/0
7     root   20    0       0      0      0   S  0.0   0.0    0:00.00    migration/0
8     root   20    0       0      0      0   S  0.0   0.0    0:00.00    rcu_bh
9     root   20    0       0      0      0   S  0.0   0.0    0:02.07    rcu_sched

我们希望关注 NI 所描绘的 NICE 列。niceness 范围可以在 -20 到正 19 之间。-20 表示给予的最高优先级。

We want to focus on the NICE column depicted by NI. The niceness range can be anywhere between -20 to positive 19. -20 represents the highest given priority.

nohup nice --20 ping www.google.com &
PID USER    PR NI  VIRT    RES  SHR  S %CPU %MEM  TIME+    COMMAND
30727 root  0 -20  132108 1640  1264 S 0.0   0.1  0:00.06   ping

renice

renice 允许我们更改当前正在运行进程的优先级。

renice allows us to change the current priority of a process that is already running.

renice 17 -p 30727

以上命令将降低 ping 进程命令的优先级。

The above command will lower the priority of our ping process command.