trap 信号捕获

命令说明

Trap signals and other events.

Defines and activates handlers to be run when the shell receives signals
or other conditions.

trap 可指定在接收到信号后将要采取的动作

示例

# 捕获 EXIT
trap "echo exit_ok" EXIT

# 捕获 SIGINT 
trap "echo exit_2" SIGINT
# 或者
trap "echo exit_2" 2
# 删除捕获
trap -- SIGINT
trap   2

# 指定多个信号
trap "echo sigspec_many" PIPE QUIT TERM INT 

#忽略信号
trap '' 2

演示
trap 演示
下面图片中,忽略信号2后,tail 中使用 Ctrl+C 失效。且shell中 无法输出^C
trap 信号忽略
使用stty -a 查看所有与终端相关的设定,使用 ^\ 退出 tail

[root@localhost ~]# stty -a
speed 38400 baud; rows 52; columns 114; line = 0;
intr = ^C; quit = ^\; erase = ^H; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q;
stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
[root@localhost ~]#

产生信号

Ctrl+Z 会产生SIGTSTP信号
Ctrl+C 会产生SIGINT信号
exit 命令产生 EXIT

语法

trap [-lp] [[arg] sigspec …]

选项说明

-p 选项而没有提供arg参数则会打印所有与sigspec指定信号相关联的的trap命令;如果没有提供任何参数或者仅有-p选项,trap命令将会打印与每一个信号有关联的命令的列表;

-l 选项的作用是让shell打印一个命令名称和其相对应的编号的列表。

示例
trap 选项示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值