16.2、信号捕捉

前端之家收集整理的这篇文章主要介绍了16.2、信号捕捉前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、信号帮助:

方法一:#man 7 signal

方法二:#kill -l

方法三:#trap -l


2、常用信号列表

Signal Value Action Comment

──────────────────────────────────────────────────────────────────────

SIGHUP 1 Term Hangup detected on controlling terminal

or death of controlling process

SIGINT 2 Term Interrupt from keyboard

SIGQUIT 3 Core Quit from keyboard

SIGILL 4 Core Illegal Instruction

SIGABRT 6 Core Abort signal from abort(3)

SIGFPE 8 Core Floating point exception

SIGKILL 9 Term Kill signal

SIGSEGV 11 Core Invalid memory reference

SIGPIPE 13 Term Broken pipe: write to pipe with no

readers

SIGALRM 14 Term Timer signal from alarm(2)

SIGTERM 15 Term Termination signal

SIGUSR1 30,10,16 Term User-defined signal 1

SIGUSR2 31,12,17 Term User-defined signal 2

SIGCHLD 20,17,18 Ign Child stopped or terminated

SIGCONT 19,18,25 Cont Continue if stopped

SIGSTOP 17,19,23 Stop Stop process

SIGTSTP 18,20,24 Stop Stop typed at terminal

SIGTTIN 21,21,26 Stop Terminal input for background process

SIGTTOU 22,22,27 Stop Terminal output for background process



3、trap:捕捉信号,

它不能捕捉9号信号(SIGKILL)和15号信号(SIGTERM),一般常用的捕捉信号是HUP和INT信号。

可以自定义捕捉信号后的处理方法


4、trap命令用法

格式:trap 'command ' signal //command为捕捉信号后要执行的命令或脚本或函数,多个命令之间用分号(;)隔开;signal为要捕捉的信号


示例1:

[root@localhost sh]# cat tr.sh

#!/bin/bash

trap 'echo "quit";exit' INT//一般把trap写在最上面,多个command之间用分号(;)隔开,

for i in {1..10};do

ping -W 1 -c 1 192.168.0.$i

done

[root@localhost sh]#


示例二:

[root@localhost sh]# cat tr2.sh

#!/bin/bash


declare -a hosttmpfiles

trap 'mytrap' INT

mytrap() {

echo "quit"

rm -rf ${hosttmpfiles[@]}

exit 1

}

for i in {1..50};do

tmpfile=$(mktemp /tmp/ping.XXXXX)

if ping -W 1 -c 1 192.168.0.$i >/dev/null;then

echo "192.168.0.$i is up" | tee $tmpfile

else

echo "192.168.0.$i is down" | tee $tmpfile

fi

hosttmpfiles[${#hosttmpfiles[*]}]=$tmpfile

done

[root@localhost sh]#





5、在bash中使用ASCII颜色:主要用在echo中,

①、\033[31m //控制颜色的开始,随后是想要加颜色显示的字符串,

##m //如31m

左侧的#:

3:表示前景色

4:表示背景色

右侧的#:1-7

1:红色

2:


②、\033[0m //控制颜色的结束


如:

[root@localhost sh]# echo "\033[31m magedu \033[0m"


③、多种控制符可以组合使用,彼此间用逗号分隔开;如

[root@localhost sh]# echo -e "\033[42;35;5m magedu \033[0m"

6:dialog:显示对话框,可实现窗口化编程;同时使得脚本显示的更人性化一些

猜你在找的CentOS相关文章