Linux-process and task management (view process command, control process, one-time and periodic scheduled task management)


One, view the process

  • A program is a static collection of executable machine code and data (code stored statically in a file) stored in an external storage medium (such as hard disk, CD)
  • A process is a computer program that is dynamically executed in the CPU and memory
  • In the Linux system, one or more processes can be created after each program is started

1. View process information-ps

  • The ps command is the most common process viewing tool in Linux systems. It is mainly used to display static snapshots containing complete information about the currently running processes.
  • Through different command options, you can selectively view process information

1.1 Method 1: ps -aux

  • a: Display all process information under the current terminal, including processes of other users. When combined with the "x" option, all process information in the system will be displayed
  • u: Output process information in a user-oriented format
  • x: Display the process information of the current user in all terminals
  • The process information will be displayed in the form of a simple list
##例:
[root@localhost ~]# ps -aux
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          1  2.6  0.3  46344  6908 ?        Ss   16:47   0:01 /usr/lib/systemd/systemd --switched-root --system --deserialize 22
root          2  0.0  0.0      0     0 ?        S    16:47   0:00 [kthreadd]
root          3  0.0  0.0      0     0 ?        S    16:47   0:00 [kworker/0:0]
root          4  0.0  0.0      0     0 ?        S<   16:47   0:00 [kworker/0:0H]
##省略...
noun Explanation
USER User of the process
PID ID of the process
%CPU The percentage of CPU occupied by the process
%MEN Percentage of memory occupied
VSZ The amount of virtual memory used by the process (KB)
RSS The amount of physical memory used by the process (KB)
TYY The name of the terminal that started the process; if the process is not started from the terminal, it will be displayed as "?"
STAT The state of the process (D: non-interruptible dormant state; R: running state; S: dormant state and can be awakened; s, parent process; T: stopped state, which may be suspended in the background or the process is in a tracking debugging state ; Z: zombie process, the process has been terminated, but most of the programs are still in memory; <: high priority state; +: foreground process) 7
START The process was triggered to start time
TIME The time the process actually uses the CPU to run
COMMAND Process start command
  • Term explanation (zombie process):
    A process has ended, but it still occupies memory, which is also called zombie

1.2 Method 2: ps -elf

  • e: Display all process information in the system
  • l: Use long format to display process information
  • f: Use complete format to display process information
  • Will display the process information in the system in a long format and contain richer content
##例:
[root@localhost ~]# ps -elf
F S UID         PID   PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
4 S root          1      0  0  80   0 - 32068 ep_pol 16:47 ?        00:00:01 /usr/lib/systemd/systemd --switched-root --system --deserialize 22
1 S root          2      0  0  80   0 -     0 kthrea 16:47 ?        00:00:00 [kthreadd]
1 S root          4      2  0  60 -20 -     0 worker 16:47 ?        00:00:00 [kworker/0:0H]
1 S root          5      2  0  80   0 -     0 worker 16:47 ?        00:00:00 [kworker/u256:0]
##省略...
noun Explanation
F System tag assigned by the kernel to the process
S Process status
UID The user who started these processes
PID Process ID of the process
PPID The process number of the parent process (if the process was started by another process)
C CPU utilization in the life cycle of a process
PRI The priority of the process (the larger the number, the lower the priority)
NI Modesty value is used to participate in determining priority
ADDR Memory address of the process
SZ If the process is swapped out, the approximate size of the swap space required
WCHAN If the process is sleeping, display the name of the system function in sleep
ESTIMATES System time when the process started
TTY Terminal device when the process starts
TIME Cumulative CPU time required to run the process
CMD Process start command

In CentOs7 system, tty1 represents the graphical interface, tty2-tty6 represents the text interface, you can use Ctrl+Alt+(F1-F6) to switch

1.3 Other examples

  • When directly executing the ps command without any options, only the processes opened in the current user session will be displayed
[root@localhost ~]# ps
   PID TTY          TIME CMD
  1803 pts/0    00:00:00 bash
  2219 pts/0    00:00:00 ps

  • Due to the large number of processes running in the system, when you need to query the information of a certain process, you can combine the pipe symbol and the grep command to filter
[root@localhost ~]# ps aux | grep bash        ##过滤出包含“bash”的信息
root        666  0.0  0.0 115408   940 ?        S    16:47   0:00 /bin/bash /usr/sbin/ksmtuned
root       1803  0.0  0.1 116328  3020 pts/0    Ss   16:47   0:00 -bash
root       2256  0.0  0.0 112828   976 pts/0    S+   17:10   0:00 grep --color=auto bash

2. View process information-top

  • Use the ps command to view a static process information, and can not continuously feedback the running status of the current process
  • If you want to display the status information of each process in a dynamic refresh mode, you can use this command
  • Refresh every three seconds by default

2.1 Example diagram

[root@localhost ~]# top

mark

2.2 System task (first line) and process (second line) information

Related Information meaning / /
18:55:08 system time Tasks Total number of processes
up 2:07 System running time running Number of running processes
1 user Number of currently logged in users sleeping Number of sleeping processes
load average:0.00,0.01,0.05 System load, that is, the number of tasks processed by the system in a unit time, the following three values ​​are the average value of 1 minute, 5 minutes, and 15 minutes to the present stopped Number of aborted processes
/ / zombie Number of zombie processes

2.3 CPU (third line), memory (fourth line) information and swap space (fifth line) information

Related Information meaning / / / /
us User occupation total Total memory space total Total swap space
his Kernel occupation free Free memory free Free swap space
ni Priority scheduling occupation used Used memory used Swap space used
id Idle CPU, to understand the percentage of idle CPU, mainly see the %id part buff / cahe The sum of the buffers of physical memory and swap memory avail Mem Available physical space
wa I/O waiting to be occupied / / / /
hi Hardware interrupt occupation / / / /
and Software interrupt occupation / / / /
st Virtualization occupancy / / / /

2.4 Detailed explanation of each column in the process information area

information Explanation
PID Process id
USER User name of the process owner
PR priority
NI Modesty value, negative value indicates high priority, positive value indicates low priority
VIRT The total amount of virtual memory used by the process, in kb
RES The size of physical memory used by the process, in kb
SHR Shared memory size, unit kb
S Process status
%CPU Percentage of CPU time from the last update to the present
%MEM The percentage of physical memory used by the process
TIME+ The total CPU time used by the process, in units of 1/100 second
COMMAND Command name/command line

2.5 TOP commonly used commands

command Explanation
P Sort by percentage of CPU usage
M Sort by size of resident memory
N Sort by start time
c Toggle display of command name and full command line
h Online help information for top program can be obtained
k Enter the PID number of the specified process as prompted and press Enter to terminate the corresponding process
q Exit top program
(Number 1 Display the number and status of CPU

3. View process information-pgrep

  • When using the ps command to query a certain process, it is often necessary to combine the grep command to filter the output results, but this is very inconvenient to use, and the "pgrep" command is a special tool used to query specific process information
  • 查询进程名中包含“log”的进程及其PID号(若没有“-l”则只输出PID号)
[root@localhost ~]# pgrep -l "log"
288 xfs-log/sda2
477 xfs-log/sda1
481 xfs-log/sda5
595 systemd-logind
601 abrt-watch-log
628 abrt-watch-log
1028 rsyslogd
  • 还可以结合“-U”选项查询特定用户的进程、“-t”选项查询在特定终端运行的进程
##例如:查询由用户 teacher 在 tty1 终端上运行的进程及PID号
[root@localhost ~]# pgrep -l -U teacher -t tty2

4.查看进程树-pstree

  • pstree命令可以输出Linux系统中各进程的树形结构,更加直观地判断出各进程之间的相互关系(如父、子进程)
  • pstree命令默认情况下只显示各进程的名称,结合“-p”选项使用时可以同时列出对应的PID号
  • 结合“-u”选项可以列出对应的用户号
  • 结合“-a”选项可以列出完整的命令信息
  • 执行“pstree -aup”命令可以查看当前系统的进程树,包括各进程对应的PID号、用户名、完整命令等信息
  • 也可以只查看属于指定用户的进程树结构,只要指定用户名作为参数即可
[root@localhost ~]# pstree -ap teacher

二、控制进程

1.进程的启动方式

  • 在Linux系统中,可以由用户手工启动或者按预定计划调度启动新的进程

1.1 手工启动

  • 根据该进程是否需要占用当前命令终端,手工启动分为以下两类
  • 前台启动:用户输入命令,直接执行程序,但得等到该进程结束并退出才能继续执行其他命令
  • 后台启动:在命令行尾加入“&”符号;无需等待,适用于等待时间较长的操作
[root@localhost ~]# cp /dev/cdrom mycd.iso &
[1] 4226
##输出信息包括后台任务序号和PID号

1.2 调动启用进程

  • 在服务器维护工作中,经常需要执行一些比较费时而且较占用资源的任务(如数据备份),这些任务更适合在相对空闲的时候(如半夜)进行
  • 但这样需要用户进行事前调度安排并指定任务运行的时间
  • 调度启动的计划任务进程均在后台运行,不占用用户的命令终端
  • 使用“at”命令,设置一次性计划任务(如24:00分时重启网络服务)
  • 使用crontab命令,设置周期性计划任务(如每周五24:00时备份数据库)

2.进程的前后台调度

2.1 挂起当前进程

  • Ctrl+Z(组合键)
  • 将当前进程挂起,即调入后台并停止执行
[root@localhost ~]# jobs -l
[1]+  5449 停止                  vim /etc/sysconfig/network-scripts/ifcfg-ens33

2.2 查看后台的进程

  • jobs
  • 查看当前终端中在后台运行的进程任务;结合“-l”选项可以同时显示出该进程的PID号
[root@localhost ~]# jobs -l
[1]+  5449 停止                  vim /etc/sysconfig/network-scripts/ifcfg-ens33

2.3 将后台的进程恢复运行

  • bg:将后台暂停执行的任务恢复运行并继续在后台执行
  • fg:将后台暂停执行的任务恢复运行并恢复到前台运作
  • 除非后台中的任务只有一个,否则bg和fg命令都需要指定后台进程的任务编号作为参数
  • 例如:“fg 1(任务编号)”

3.终止进程执行

  • 当用户在前台执行某个进程时,可以用Ctrl+C组合键强制中断当前正在执行的命令

3.1 kill

  • kill用于终止指定PID号的进程,需要使用进程的PID号作为参数
[root@localhost ~]# pgrep -l "sshd"        ##查询目标进程PID号
1026 sshd
1798 sshd
[root@localhost ~]# kill 1026        ##终止指定PID的进程
[root@localhost ~]# pgrep -l "sshd"
1798 sshd        ##再查询时,发现1026没有了,进程已成功终止
  • 若该进程不响应终止信号,则结合“-9”选项可以强制终止
  • 强制终止可能导致数据丢失,慎用
[root@localhost ~]# vim tmpfile        ##打开vim并挂起以作测试

[1]+  已停止               vim tmpfile
[root@localhost ~]# jobs -l        ##查询目标进程PID号
[1]+  2028 停止                  vim tmpfile
[root@localhost ~]# kill 2028        ##尝试直接终止进程
[root@localhost ~]# jobs -l        ##查询后发现并未退出
[1]+  2028 停止                  vim tmpfile
[root@localhost ~]# kill -9 2028        ##结合“-9”选项试试,强制终止目标进程
[root@localhost ~]# jobs -l        ##没了,成功
[1]+  2028 已杀死               vim tmpfile

3.2 killall

  • 用于结束系统中多个相关名称的进程
  • 也可以结合“-9”选项
  • 例:执行“killall -9 vim”命令可将所有名为vim的进程全部强行终止
[root@localhost ~]# vim testfile1

[1]+  已停止               vim testfile1
[root@localhost ~]# vim testfile2

[2]+  已停止               vim testfile2
[root@localhost ~]# vim testfile3

[3]+  已停止               vim testfile3
[root@localhost ~]# jobs -l
[1]   2130 停止                  vim testfile1
[2]-  2131 停止                  vim testfile2
[3]+  2132 停止                  vim testfile3
[root@localhost ~]# killall -9 vim
[1]   已杀死               vim testfile1
[2]-  已杀死               vim testfile2
[3]+  已杀死               vim testfile3

3.3 pkill

  • 根据进程的名称、运行该进程的用户、进程所在的终端等多种属性终止特定的进程
  • 与“pgrep”命令选项类似,如“-U(指定用户名)”、“-t(指定终端)”

三、一次性计划任务-at

  • 设置一次性计划时,在at命令中依次指定计划执行任务的时间、日期作为参数
  • 确认后进入带“at>”提示符的任务编辑器界面,每行设置一条执行命令,可以依次设置多条语句,最后按Ctrl+D组合键提交任务
  • 注:计划执行任务的时间、日期必须安排在当前系统时间之后
  • 对应条件:对应系统服务为atd,必须已经运行
  • 示例:
##设置在当天的20:00时关机
[root@localhost ~]# at 20:00
at> init 0<EOT>        ##Ctrl+D组合键提交任务(按2次)
job 7 at Tue Dec  1 20:00:00 2020
  • “atq”命令可以进行查询,已执行过的不会再出现在列表中
[root@localhost ~]# atq
7	Tue Dec  1 20:00:00 2020 a root
  • "atrm"命令可以删除指定编号的at任务
[root@localhost ~]# atrm 7
[root@localhost ~]# atq
[root@localhost ~]# 

四、计划任务管理-crontab

  • 使用crontab命令设置的计划任务可以按预设的周期重复执行,可以大大减轻设置重复性系统管理任务的操作
  • 由软件包cronie提供crontab工具、系统服务crond和配置文件/etc/crontab
  • 前提条件:对应的系统服务crond必须已经运行

1.配置文件和目录

  • crond通过多个目录和文件设置计划任务,不同类型的任务由不同的配置文件来设置

1.1 系统任务配置文件,位于文件:/etc/crontab

  • 设置的是维护Linux系统所需的任务,由Linux系统及相关程序在安装时自动设置,不建议用户修改

1.2 The system default settings, located in the directory: /etc/cron.*/

  • After the crontabs package is installed, some scheduled task directories set by the system default will be promoted in this directory, and what work the system does every hour and every day is set

1.3 User-defined settings, located in the file: /var/spool/cron/

  • The cron plan set by the user using the crontab command will be saved in this directory (a file with the same user name will be generated in this directory)

2. Manage crontab scheduled tasks

  • -u: Specify which user the scheduled task belongs to. By default, it is for the current user (self); generally only the root user has permission to use this option
  • Edit the scheduled task
    crontab -e [-u username] (when there is no -u, the default object is the current user)
  • View the scheduled task
    crontab -l [-u username]
  • Delete the scheduled task
    crontab -r [-u username]

3. The format of crontab task configuration

mark

Field Description
minute The value is any integer from 0 to 59
hour The value is any integer from 0 to 23
date The value is any integer from 1 to 31
month The value is any integer from 1 to 12
week The value is any integer from 0 to 7, 0 or 7 represents Sunday
command Command or program script to execute
  • Remember the formula (keep in mind):
    time-sharing day, month and week

4. Special representation method of time value

  • "*" means any time within the range
  • "," means multiple discrete time points in an interval
  • "-" means a continuous time range
  • "/" indicates the time frequency of the interval
  • Example:
0 17 * * 1-5          ##周一到周五每天17:00
30 8 * * 1,3,5        ##每周(一、三、五)的8:30
0 8-18/2 * * *        ##8点到18点之间每2个小时
0 * */3 * *           ##每3天
  • Because no user login is required to perform tasks, it is recommended to use absolute paths to avoid the situation where commands cannot be executed due to lack of execution paths
  • When setting the task to be executed every minute, the "minute" field should also be filled in with a specific time value instead of the default "*", otherwise the task will be executed every minute

5. Other

  • The crontab command set "-l" option can view the current user's scheduled task list. For root users, you can also combine the "-u" option to view other users' scheduled tasks
  • When you need to delete a scheduled task, you can edit it with the "-e" option
  • Other examples:
5 * * * * ls        ##每个小时的第5分钟执行一次ls命令
30 5 * * * ls       ##每天的5:30执行ls命令
30 7 8 * * ls       ##每个月8号的7:30执行ls命令
30 5 8 6 * ls       ##每个6月8号的5:30执行ls命令
30 6 * * 0 ls       ##每个周日的6:30执行ls命令
30 3 10,20 * * ls   ##每个月10号和20号的3:30执行ls命令
25 8-11 * * * ls    ##每天8点到11点的第25分时执行ls命令
*/15 * * * * ls     ##每隔15分钟执行一次ls命令
30 6 */10 * * ls    ##月中的每隔10天的6:30时执行一次ls命令

Guess you like

Origin blog.csdn.net/weixin_51486343/article/details/110439089