Day 07 Process Management + Task Management

Day 07 Process Management + Task Management

1. Introduction

1. What is a process

For example: We call the developed code a program, then run the developed code. We call it a process.
The summary is: when we run a program, then the program we will run is called a process.
PS1: When the program runs as a process, the system will allocate memory for the process, as well as the identity and permissions of the process.
PS2: During the process of running, the system will have various indicators to indicate the current running status.

2. The difference between program and process

1. A program is a collection of data and instructions, a static concept. For example, binary files such as /bin/ls and /bin/cp. At the same time, the program can exist in the system for a long time.
2. Process is the process of program running, which is a dynamic concept. The process has the concept of life cycle, which means that the process will be destroyed with the termination of the program, and will not permanently exist in the system.

3. The life cycle of the process

Life cycle refers to the birth, aging, sickness and death of an object. Very useful.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-f3qv7Zm2-1606475048540)(https://i.loli.net/2020/11/27/E3XxNeh6bR1s4ad.jpg )]

When the parent process receives the task scheduling, it will derive the child process through fock to handle it, then the child process will inherit the parent process attributes.
1. When the child process is processing the task code, the parent process will enter the waiting state...
2. After the child process processes the task code, it will exit, and then wake up the parent process to reclaim the resources of the child process.
3. If the parent process exits while the child process is processing tasks, but the child process does not exit, then these child processes will not be managed by the parent process, and become zombie processes.
PS: Each process has the PPID of the parent process, and the child process is called PID.

Example: Assuming that I am Mr. Jiang (system process)... The story continues...

2. Monitor process status

After the program is running, we need to know the running status of the process. There are two ways to view the status of the process: static and dynamic

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-gEmn2lGH-1606475048541)(https://i.loli.net/2020/11/27/v9bxJZVwNkeOH6n.png )]

status description
USER The user who started the process
PID ID number of the process running
%CPU The percentage of CPU occupied by the process
%MEM Percentage of memory occupied by the process
VSZ The size of virtual memory occupied by the process (in KB)
RSS The actual size of the physical memory occupied by the process (in KB)
TTY Which terminal is the process started by tty1, pts/0, etc.? Means that the kernel program has nothing to do with the terminal (a remote connection will open a bash through tty: tty)
STAT The state of the process during operation man ps (/STATE)
START Process start time
TIME The total time the process occupies the CPU (0 means it has not exceeded the second)
COMMAND The running instructions of the program, [square brackets] belong to the kernel mode process. The ones without [] are user-mode processes. systemctl status command

2. What do the STAT status S, Ss, S+, R, R, S+, etc. mean?

STAT basic status description STAT status + sign description
R Process running s The process is the control process, the leader of the Ss process, the parent process
S Interruptible sleep < The process is running at a high priority, S <a process with a higher priority
T Process is suspended N The process is running at low priority, the process with lower SN priority
D Uninterrupted sleep + The current process is running in the foreground, R+ means that the process is running in the foreground (the io operation is in progress, once stopped, the data will be lost)
X Dead process Dead process (almost invisible, because it is reclaimed immediately)
WITH Zombie process l The process is multi-threaded, Sl means that the process is running in threads

Case 1: PS command to view process status switch

vim testfiled  # 创建并编辑文件testfiled

ps aux|grep testfiled  # 查看相关进程
------------------------------------------------------------------------
root      6376  0.0  0.0 112812   972 pts/0    S+   15:29   0:00 grep --color=auto testfiled
# 一个终端运行,前台显示的可中断睡眠进程

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-eQtbD9Ms-1606475048543)(https://i.loli.net/2020/11/27/Hb9CVJqor8ZuMlO.jpg )]

task meaning
Tasks: 129 total Of course the total number of processes
1 running Number of running processes
128 sleeping Number of sleeping processes
0 stopped Number of stopped processes
0 zombie Number of zombie processes
%Cpu(s) Average CPU usage, press 1 to view the specific status of each cup
0.7 us Percentage of CPU occupied by user processes
0.7 sys Percentage occupied by kernel processes
0.0 ni Percentage of CPU occupied by priority processes
98.7 id Free cup
0.0 wa The time the CPU waits for IO to complete, a lot of IO waits, will become high
0.0 hi Hard interrupt, percentage of CPU
0.0 si Soft interrupt, percentage of CPU
0.0 st The time the virtual machine occupies the physical CPU
# w     load average:平均负载 一分钟,5分钟,15分钟
 04:05:43 up 11:35,  3 users,  load average: 0.00, 0.01, 0.05
# uptime
 04:06:21 up 11:35,  3 users,  load average: 0.00, 0.01, 0.05

top command

letter meaning
h View help out
1 Number 1, shows the load of all CPU cores
with To highlight data
b Highlight processes in R (in progress) state
M Sort output by percentage of memory usage
P Sort output by CPU usage percentage
q Exit top
# 第三方top
htop,top高级:yum install htop -y
iftop网卡流量:yum install iftop -y
glances,直观的显示:yum install glances -y
  -rz上传文件,可以动态看到,网卡情况

3. Manage process status

After the program is running as a process, what should we do if we want to stop the process? Then we can use the linux kill command to send a shutdown signal to the process. Of course, in addition to kill, there are killall, pkill

1. Use kill -l to list the signals supported by the current system

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-JFA1MfKI-1606475048545)(https://i.loli.net/2020/11/27/s3LtgMZPY1SxNf4.png )]

Although Linux supports many signals, we only list the 3 most commonly used signals

Digital number Signal meaning Signal translation
1 SIGHUP Usually used to reload the configuration file and re-read the parameter configuration file (similar to reload)
9 SIGKILL Forced to kill the process (a stateful service (disk storage, such as mysql) forced to stop may cause the next time to fail)
15 SIGTERM 终止进程,默认kill使用该信号

1.我们使用kill命令杀死指定PID的进程。

#1.给 vsftpd 进程发送信号 1,15
[root@lqz ~]# yum -y install vsftpd
[root@lqz ~]# systemctl start vsftpd
[root@lqz ~]# ps aux|grep vsftpd

#2.发送重载信号,例如 vsftpd 的配置文件发生改变,希望重新加载
[root@lqz ~]# kill -1 9160

#3.发送停止信号,当然vsftpd 服务有停止的脚本 systemctl stop vsftpd
[root@lqz ~]# kill 9160

#4.发送强制停止信号,当无法停止服务时,可强制终止信号
[root@lqz ~]# kill -9 9160

2.Linux系统中的killall、pkill命令用于杀死指定名字的进程。我们可以使用kill命令杀死指定进程PID的进程,如果要找到我们需要杀死的进程,我们还需要在之前使用ps等命令再配合grep来查找进程,而killall、pkill把这两个过程合二为一,是一个很好用的命令。

#例0、通过服务名称杀掉进程
[root@lqz ~]# vim nginx.conf   # 修改为worker_processes  10;
[root@lqz ~]# kill -1 26093    # 平滑reload nginx,可以看到很多ngixn进程
[root@lqz ~]# kill 26121      # 杀掉一个子进程,会迅速的被master启动起来,只是id号不一致了

[root@lqz ~]# kill  26093    # 主进程,子进程都会被杀掉 

#例1、通过服务名称杀掉进程
[root@lqz ~]# pkill nginx
[root@lqz ~]# killall nginx

#例2、使用pkill踢出从远程登录到本机的用户,终止pts/0上所有进程, 并且bash也结束(用户被强制退出)
[root@lqz ~]# pkill -9 bash

# 一般程序都会有自己的启动和停止
/usr/local/nginx/sbin/nginx -h

4.管理后台进程

1.什么是后台进程

通常进程都会在终端前台运行,一旦关闭终端,进程也会随着结束,那么此时我们就希望进程能在后台运行,就是将在前台运行的进程放入后台运行,这样及时我们关闭了终端也不影响进程的正常运行。

2.我们为什么要将进程放入后台运行

比如:我们此前在国内服务器往国外服务器传输大文件时,由于网络的问题需要传输很久,如果在传输的过程中出现网络抖动或者不小心关闭了终端则会导致传输失败,如果能将传输的进程放入后台,是不是就能解决此类问题了。

3.使用什么工具将进程放入后台

早期的时候大家都选择使用&符号将进程放入后台,然后在使用jobs、bg、fg等方式查看进程状态,但太麻烦了。也不直观,所以我们推荐使用screen。

1.jobs、bg、fg的使用(强烈不推荐,了解即可)

[root@lqz ~]# sleep 3000 & //运行程序(时),让其在后台执行 
[root@lqz ~]# sleep 4000 //^Z,将前台的程序挂起(暂停)到后台 
[2]+ Stopped sleep 4000
[root@lqz ~]# ps aux |grep sleep
[root@lqz ~]# jobs  //查看后台作业
[1]- Running sleep 3000 & 
[2]+ Stopped sleep 4000

[root@lqz ~]# bg %2     //让作业 2 在后台运行
[root@lqz ~]# fg %1     //将作业 1 调回到前台
[root@lqz ~]# kill %1   //kill 1,终止 PID 为 1 的进程

[root@lqz ~]# (while :; do date; sleep 2; done) & //进程在后台运行,但输出依然在当前终端
[root@lqz ~]# (while :; do date; sleep 2; done) &>/dev/null &

2.screen的使用(强烈推荐,生产必用)

#1.安装
[root@oldboy ~]# yum install screen -y

#2.开启一个screen窗口,指定名称
[root@oldboy ~]# screen -S wget_mysql

#3.在screen窗口中执行任务即可
[root@oldboy ~]# wget https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.30-linux-glibc2.12-x86_64.tar.gz --no-check-certificate

#4.平滑的退出screen,但不会终止screen中的任务。注意: 如果使用exit 才算真的关闭screen窗口
ctrl+a+d

#5.查看当前正在运行的screen有哪些
[root@oldboy ~]# screen -list
There is a screen on:
    22058.wget_mysql    (Detached)
1 Socket in /var/run/screen/S-root.

#6.进入正在运行的screen
[root@oldboy ~]# screen -r wget_mysql
[root@oldboy ~]# screen -r 22058

#7 终止(ctrl+d),退出才能停止screen
exit

5.进程的优先级[进阶]

1.什么优先级

优先级指的是优先享受资源,比如排队买票时,军人优先、老人优先。等等

2.为什么要有系统优先级

举个例子: 海底捞火锅正常情况下响应就特别快,那么当节假日来临时人员突增则会导致处理请求特别慢,那么假设我是海底捞VIP客户(最高优先级),无论门店多么繁忙,我都不用排队,海底捞人员会直接服务于我,满足我的需求。至于没有VIP的人员(较低优先级)则进入排队等待状态。(PS: 至于等多久,那……)

3.系统中如何给进程配置优先级?

在启动进程时,为不同的进程使用不同的调度策略。
nice 值越高: 表示优先级越低,例如+19,该进程容易将CPU 使用量让给其他进程。
nice 值越低: 表示优先级越高,例如-20,该进程更不倾向于让出CPU。

  1. 使用top或ps命令查看进程的优先级
#1.使用top可以查看nice优先级。  
NI: 实际nice级别,默认是0。 
PR: 显示nice值,-20映射到0,+19映射到39

PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
1083 root      20   0  298628   2808   1544 S  0.3  0.1   2:49.28 vmtoolsd
5    root       0 -20       0      0      0 S  0.0  0.0   0:00.00 kworker/0:+

#2.使用ps查看进程优先级
[root@m01 ~]# ps axo command,nice |grep sshd|grep -v grep
/usr/sbin/sshd -D             0
sshd: root@pts/2              0
  1. nice指定程序的优先级。语法格式 nice -n 优先级数字 进程名称
#1.开启vim并且指定程序优先级为-5
[root@m01 ~]# nice -n -5 vim &
[1] 98417

#2.查看该进程的优先级情况
[root@m01 ~]# ps axo pid,command,nice |grep 98417
 98417 vim                         -5
  1. renice命令修改一个正在运行的进程优先级。语法格式 renice -n 优先级数字 进程pid
#1.查看sshd进程当前的优先级状态
[root@m01 ~]# ps axo pid,command,nice |grep 折叠shd
 70840 sshd: root@pts/2              0
 98002 /usr/sbin/sshd -D             0
 
#2.调整sshd主进程的优先级
[root@m01 ~]# renice -n -20 98002
98002 (process ID) old priority 0, new priority -20

#3.调整之后记得退出终端
[root@m01 ~]# ps axo pid,command,nice |grep 折叠shd
 70840 sshd: root@pts/2              0
 98002 /usr/sbin/sshd -D           -20
[root@m01 ~]# exit

#4.当再次登陆sshd服务,会由主进程fork子进程(那么子进程会继承主进程的优先级)
[root@m01 ~]# ps axo pid,command,nice |grep 折叠shd
 98002 /usr/sbin/sshd -D           -20
 98122 sshd: root@pts/0            -20

生产案例、Linux出现假死,怎么办,又如何通过nice解决?

6.系统平均负载[进阶]

每次发现系统变慢时,我们通常做的第一件事,就是执行 top 或者 uptime 命令,来了解系统的负载情况。比如像下面这样,我在命令行里输入了 uptime 命令,系统也随即给出了结果。

[root@m01 ~]# uptime
 04:49:26 up 2 days,  2:33,  2 users,  load average: 0.70, 0.04, 0.05
#我们已经比较熟悉前面几列,它们分别是当前时间、系统运行时间以及正在登录用户数。

# 而最后三个数字呢,依次则是过去 1 分钟、5 分钟、15 分钟的平均负载(Load Average)。

1.什么是平均负载

平均负载不就是单位时间内的 CPU 使用率吗?上面的 0.70,就代表 CPU 使用率是 70%。其实上并……
那到底如何理解平均负载: 平均负载是指单位时间内,系统处于可运行状态和不可中断状态的平均进程数,也就是平均活跃进程数, PS: 平均负载与 CPU 使用率并没有直接关系

2.可运行状态和不可中断状态是什么

1.可运行状态进程,是指正在使用 CPU 或者正在等待 CPU 的进程,也就是我们ps 命令看到处于 R 状态的进程。
2.不可中断进程,(你做什么事情的时候是不能打断的?) 系统中最常见的是等待硬件设备的 I/O 响应,也就是我们 ps 命令中看到的 D 状态(也称为 Disk Sleep)的进程。
例如: 当一个进程向磁盘读写数据时,为了保证数据的一致性,在得到磁盘回复前,它是不能被其他进程或者中断打断的,这个时候的进程就处于不可中断状态。如果此时的进程被打断了,就容易出现磁盘数据与进程数据不一致的问题。所以,不可中断状态实际上是系统对进程和硬件设备的一种保护机制。

划重点,因此你可以简单理解为,平均负载其实就是单位时间内的活跃进程数

3.那平均负载为多少时合理

最理想的状态是每个 CPU 上都刚好运行着一个进程,这样每个 CPU 都得到了充分利用。所以在评判平均负载时,首先你要知道系统有几个 CPU,这可以通过 top 命令获取,或grep 'model name' /proc/cpuinfo

例1、假设现在在 4、2、1核的CPU上,如果平均负载为 2 时,意味着什么呢?
Q1.在4 个 CPU 的系统上,意味着 CPU 有 50% 的空闲。
Q2.在2 个 CPU 的系统上,意味着所有的 CPU 都刚好被完全占用。
Q3.而1 个 CPU 的系统上,则意味着有一半的进程竞争不到 CPU。

PS: 平均负载有三个数值,我们应该关注哪个呢?
实际上,我们都需要关注。就好比上海4月的天气,如果只看晚上天气,感觉在过冬天呢。但如果你结合了早上、中午、晚上三个时间点的温度来看,基本就可以全方位了解这一天的天气情况了。

1.如果 1 分钟、5 分钟、15 分钟的三个值基本相同,或者相差不大,那就说明系统负载很平稳。
2.但如果 1 分钟的值远小于 15 分钟的值,就说明系统最近 1 分钟的负载在减少,而过去 15 分钟内却有很大的负载。
3.反过来,如果 1 分钟的值远大于 15 分钟的值,就说明最近 1 分钟的负载在增加,这种增加有可能只是临时性的,也有可能还会持续上升,所以就需要持续观察。
PS: 一旦 1 分钟的平均负载接近或超过了 CPU 的个数,就意味着系统正在发生过载的问题,这时就得分析问题,并要想办法优化了

在来看个例子3、假设我们在有2个 CPU 系统上看到平均负载为 2.73,6.90,12.98
那么说明在过去1 分钟内,系统有 136% 的超载 (2.73/2=136%)
而在过去 5 分钟内,有 345% 的超载 (6.90/2=345%)
而在过去15 分钟内,有 649% 的超载,(12.98/2=649%)
但从整体趋势来看,系统的负载是在逐步的降低。

4.那么在实际生产环境中,平均负载多高时,需要我们重点关注呢?

当平均负载高于 CPU 数量 70% 的时候,你就应该分析排查负载高的问题了。一旦负载过高,就可能导致进程响应变慢,进而影响服务的正常功能。
但 70% 这个数字并不是绝对的,最推荐的方法,还是把系统的平均负载监控起来,然后根据更多的历史数据,判断负载的变化趋势。当发现负载有明显升高趋势时,比如说负载翻倍了,你再去做分析和调查。

5.平均负载与 CPU 使用率有什么关系

在实际工作中,我们经常容易把平均负载和 CPU 使用率混淆,所以在这里,我也做一个区分。可能你会疑惑,既然平均负载代表的是活跃进程数,那平均负载高了,不就意味着 CPU 使用率高吗?
我们还是要回到平均负载的含义上来,平均负载是指单位时间内,处于可运行状态和不可中断状态的进程数。所以,它不仅包括了正在使用 CPU 的进程,还包括等待 CPU 和等待 I/O 的进程。

而 CPU 使用率,是单位时间内 CPU 繁忙情况的统计,跟平均负载并不一定完全对应。比如:
CPU 密集型进程,使用大量 CPU 会导致平均负载升高,此时这两者是一致的;
I/O 密集型进程,等待 I/O 也会导致平均负载升高,但 CPU 使用率不一定很高;
大量等待 CPU 的进程调度也会导致平均负载升高,此时的 CPU 使用率也会比较高。

6.平均负载案例分析实战

下面,我们以三个示例分别来看这三种情况,并用 stress、mpstat、pidstat 等工具,找出平均负载升高的根源。
stress 是 Linux 系统压力测试工具,这里我们用作异常进程模拟平均负载升高的场景。
mpstat 是多核 CPU 性能分析工具,用来实时查看每个 CPU 的性能指标,以及所有 CPU 的平均指标。
pidstat 是一个常用的进程性能分析工具,用来实时查看进程的 CPU、内存、I/O 以及上下文切换等性能指标。

#如果出现无法使用mpstat、pidstat命令查看%wait指标建议更新下软件包
wget http://pagesperso-orange.fr/sebastien.godard/sysstat-11.7.3-1.x86_64.rpm
rpm -Uvh sysstat-11.7.3-1.x86_64.rpm

场景一:CPU 密集型进程

1.首先,我们在第一个终端运行 stress 命令,模拟一个 CPU 使用率 100% 的场景:

[root@m01 ~]# stress --cpu 1 --timeout 600

2.接着,在第二个终端运行 uptime 查看平均负载的变化情况

# 使用watch -d 参数表示高亮显示变化的区域(注意负载会持续升高)
[root@m01 ~]# watch -d uptime
17:27:44 up 2 days,  3:11,  3 users,  load average: 1.10, 0.30, 0.17

3.最后,在第三个终端运行 mpstat 查看 CPU 使用率的变化情况

# -P ALL 表示监控所有 CPU,后面数字 5 表示间隔 5 秒后输出一组数据
[root@m01 ~]# mpstat -P ALL 5
Linux 3.10.0-957.1.3.el7.x86_64 (m01)   2019年04月29日     _x86_64_    (1 CPU)

17时32分03秒  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
17时32分08秒  all   99.80    0.00    0.20    0.00    0.00    0.00    0.00    0.00    0.00    0.00
17时32分08秒    0   99.80    0.00    0.20    0.00    0.00    0.00    0.00    0.00    0.00    0.00

#单核CPU所以只有一个all和0

4.从终端二中可以看到,1 分钟的平均负载会慢慢增加到 1.00,而从终端三中还可以看到,正好有一个 CPU 的使用率为 100%,但它的 iowait 只有 0。这说明,平均负载的升高正是由于 CPU 使用率为 100% 。那么,到底是哪个进程导致了 CPU 使用率为 100% 呢?可以使用 pidstat 来查询

# 间隔 5 秒后输出一组数据
[root@m01 ~]# pidstat -u 5 1
Linux 3.10.0-957.1.3.el7.x86_64 (m01)   2019年04月29日     _x86_64_(1 CPU)

17时33分21秒   UID       PID    %usr %system  %guest    %CPU   CPU  Command
17时33分26秒     0    110019   98.80    0.00    0.00   98.80     0  stress

#从这里可以明显看到,stress 进程的 CPU 使用率为 100%。

场景二:I/O 密集型进程

1.首先还是运行 stress 命令,但这次模拟 I/O 压力,即不停地执行 sync

[root@m01 ~]# stress  --io 1 --timeout 600s

2.然后在第二个终端运行 uptime 查看平均负载的变化情况:

[root@m01 ~]# watch -d uptime
18:43:51 up 2 days,  4:27,  3 users,  load average: 1.12, 0.65, 0.00

3.最后第三个终端运行 mpstat 查看 CPU 使用率的变化情况:

# 显示所有 CPU 的指标,并在间隔 5 秒输出一组数据
[root@m01 ~]# mpstat -P ALL 5
Linux 3.10.0-693.2.2.el7.x86_64 (bgx.com)   2019年05月07日     _x86_64_    (1 CPU)

14时20分07秒  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
14时20分12秒  all    0.20    0.00   82.45   17.35    0.00    0.00    0.00    0.00    0.00    0.00
14时20分12秒    0    0.20    0.00   82.45   17.35    0.00    0.00    0.00    0.00    0.00    0.00

#会发现cpu的与内核打交道的sys占用非常高

4.那么到底是哪个进程,导致 iowait 这么高呢?我们还是用 pidstat 来查询

# 间隔 5 秒后输出一组数据,-u 表示 CPU 指标
[root@m01 ~]# pidstat -u 5 1
Linux 3.10.0-957.1.3.el7.x86_64 (m01)   2019年04月29日     _x86_64_(1 CPU)
18时29分37秒   UID       PID    %usr %system  %guest   %wait    %CPU   CPU  Command
18时29分42秒     0    127259   32.60    0.20    0.00   67.20   32.80     0  stress
18时29分42秒     0    127261    4.60   28.20    0.00   67.20   32.80     0  stress
18时29分42秒     0    127262    4.20   28.60    0.00   67.20   32.80     0  stress

#可以发现,还是 stress 进程导致的。

场景三:大量进程的场景
当系统中运行进程超出 CPU 运行能力时,就会出现等待 CPU 的进程。

1.首先,我们还是使用 stress,但这次模拟的是 4 个进程

[root@m01 ~]# stress -c 4 --timeout 600

2.由于系统只有 1 个 CPU,明显比 4 个进程要少得多,因而,系统的 CPU 处于严重过载状态

[root@m01 ~]# watch -d uptime
19:11:07 up 2 days,  4:45,  3 users,  load average: 4.65, 2.65, 4.65

3.然后,再运行 pidstat 来看一下进程的情况:

# 间隔 5 秒后输出一组数据
[root@m01 ~]# pidstat -u 5 1
平均时间:   UID       PID    %usr %system  %guest   %wait    %CPU   CPU  Command
平均时间:     0    130290   24.55    0.00    0.00   75.25   24.55     -  stress
平均时间:     0    130291   24.95    0.00    0.00   75.25   24.95     -  stress
平均时间:     0    130292   24.95    0.00    0.00   75.25   24.95     -  stress
平均时间:     0    130293   24.75    0.00    0.00   74.65   24.75     -  stress

可以看出,4 个进程在争抢 1 个 CPU,每个进程等待 CPU 的时间(也就是代码块中的 %wait 列)高达 75%。这些超出 CPU 计算能力的进程,最终导致 CPU 过载。

分析完这三个案例,我再来归纳一下平均负载与CPU
平均负载提供了一个快速查看系统整体性能的手段,反映了整体的负载情况。但只看平均负载本身,我们并不能直接发现,到底是哪里出现了瓶颈。所以,在理解平均负载时,也要注意:
平均负载高有可能是 CPU 密集型进程导致的;
平均负载高并不一定代表 CPU 使用率高,还有可能是 I/O 更繁忙了;
当发现负载高的时候,你可以使用 mpstat、pidstat 等工具,辅助分析负载的来源

1.计划任务基本概述

1.什么是crond

crond就是计划任务,类似于我们平时生活中的闹钟。定点执行。

2.为什么要使用crond
crond主要是做一些周期性的任务,比如: 凌晨3点定时备份数据。比如:11点开启网站抢购接口,12点关闭网站抢购接口。

3.计划任务主要分为以下两种使用情况:

1.系统级别的定时任务: 临时文件清理、系统信息采集、日志文件切割
2.用户级别的定时任务: 定时向互联网同步时间、定时备份系统配置文件、定时备份数据库的数据

2.计划任务时间管理

1.Crontab配置文件记录了时间周期的含义

[root@lqz ~]# vim /etc/crontab
SHELL=/bin/bash                     #执行命令的解释器
PATH=/sbin:/bin:/usr/sbin:/usr/bin  #环境变量
MAILTO=root                         #邮件发给谁
# Example of job definition:
# .---------------- minute (0 - 59) #分钟
# |  .------------- hour (0 - 23)   #小时
# |  |  .---------- day of month (1 - 31)   #日期
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr #月份
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat  #星期
# |  |  |  |  |
#            command to be executed

#   表示任意的(分、时、日、月、周)时间都执行
# -  表示一个时间范围段, 如5-7点
# ,  表示分隔时段, 如6,0,4表示周六、日、四
# /1 表示每隔n单位时间, 如/10 每10分钟

2.了解crontab的时间编写规范

00 02    ls      #每天的凌晨2点整执行
00 02 1   ls      #每月的1日的凌晨2点整执行
00 02 14 2  ls     #每年的2月14日凌晨2点执行
00 02   7 ls      #每周天的凌晨2点整执行
00 02  6 5 ls      #每年的6月周五凌晨2点执行
00 02 14  7 ls     #每月14日或每周日的凌晨2点都执行
00 02 14 2 7 ls     #每年的2月14日或每年2月的周天的凌晨2点执行   
/10  02    ls   #每天凌晨2点,每隔10分钟执行一次
      ls       #每分钟都执行
00 00 14 2   ls    #每年2月14日的凌晨执行命令 
/5      ls     #每隔5分钟执行一次
00 02  1,5,8  ls  #每年的1月5月8月凌晨2点执行
00 02 1-8    ls    #每月1号到8号凌晨2点执行
0 21    ls       #每天晚上21:00执行
45 4 1,10,22   ls #每月1、10、22日的4:45执行
45 4 1-10   l     #每月1到10日的4:45执行
3,15 8-11 /2   ls #每隔两天的上午8点到11点的第3和第15分钟执行
0 23-7/1    ls   #晚上11点到早上7点之间,每隔一小时执行
15 21   1-5 ls    #周一到周五每天晚上21:15执行

3.使用crontab编写cron定时任务

参数 含义
-e 编辑定时任务
-l 查看定时任务
-r 删除定时任务
-u 指定其他用户

3.计划任务编写实践

1.使用root用户每5分钟执行一次时间同步

#1.如何同步时间
[root@lqz ~]# ntpdate time.windows.com &>/dev/null
#2.配置定时任务
[root@lqz ~]# crontab -e -u root
[root@lqz ~]# crontab -l -u root
/5     ntpdate time.windows.com &>/dev/null

2.每天的下午3,5点,每隔半小时执行一次sync命令

[root@lqz ~]# crontab -l
/30 15,17    sync &>/dev/null

3.案例:每天凌晨3点做一次备份?备份/etc/目录到/backup下面

  1. 将备份命令写入一个脚本中
  2. 每天备份文件名要求格式: 2019-05-01_hostname_etc.tar.gz
  3. 在执行计划任务时,不要输出任务信息
  4. 存放备份内容的目录要求只保留三天的数据
#1.实现如上备份需求
[root@lqz ~]# mkdir /backup
[root@lqz ~]# tar zcf $(date +%F)_$(hostname)_etc.tar.gz /etc
[root@lqz ~]# find /backup -name “.tar.gz” -mtime +3 -exec rm -f {};

#2.将命令写入至一个文件中
[root@lqz ~]# vim /root/back.sh
mkdir /backup
tar zcf $(date +%F)_$(hostname)_etc.tar.gz /etc
find /backup -name “.tar.gz” -mtime +3 -exec rm -f {};

#3.配置定时任务
[root@lqz ~]# crontab -l
00 03    bash /root/back.sh  &>/dev/null

#3.备份脚本

4.crond注意的事项

  1. 给定时任务注释
  2. 将需要定期执行的任务写入Shell脚本中,避免直接使用命令无法执行的情况tar date
  3. 定时任务的结尾一定要有&>/dev/null或者将结果追加重定向>>/tmp/date.log文件
  4. 注意有些命令是无法成功执行的 echo “123” >>/tmp/test.log &>/dev/null
    5.如果一定要是用命令,命令必须使用绝对路径

5.crond如何备份

  1. 通过查找/var/log/cron中执行的记录,去推算任务执行的时间
  2. 定时的备份/var/spool/cron/{usernmae}

6.crond如何拒绝某个用户使用

#1.使用root将需要拒绝的用户加入/etc/cron.deny
[root@lqz ~]# echo "lqz" >> /etc/cron.deny

#2.登陆该普通用户,测试是否能编写定时任务
[oldboy@lqz ~]$ crontab -e
You (lqz) are not allowed to use this program (crontab)
See crontab(1) for more information

4.计划任务如何调试

1.crond调试

  1. 调整任务每分钟执行的频率, 以便做后续的调试。
  2. 如果使用cron运行脚本,请将脚本执行的结果写入指定日志文件, 观察日志内容是否正常。
  3. 命令使用绝对路径, 防止无法找到命令导致定时任务执行产生故障。
  4. 通过查看/var/log/cron日志,以便检查我们执行的结果,方便进行调试。

2.crond编写思路

  • 1.手动执行命令,然后保留执行成功的结果。
  • 2.编写脚本
    • 脚本需要统一路径/scripts
    • 脚本内容复制执行成功的命令(减少每个环节出错几率)
    • 脚本内容尽可能的优化, 使用一些变量或使用简单的判断语句
    • 脚本执行的输出信息可以重定向至其他位置保留或写入/dev/null
  • 3.执行脚本
    • 使用bash命令执行, 防止脚本没有增加执行权限(/usr/bin/bash)
    • 执行脚本成功后,复制该执行的命令,以便写入cron
  • 4.编写计划任务
    • 加上必要的注释信息, 人、时间、任务
    • 设定计划任务执行的周期
    • 粘贴执行脚本的命令(不要手敲)
  • 5.调试计划任务
    • 增加任务频率测试
    • 检查环境变量问题
    • 检查crond服务日志

Guess you like

Origin blog.csdn.net/A1L__/article/details/110241087