ksh trap signal


What's Signal


When a signal is received, a script can do one of three actions:

  1. Ignore it and do nothing.
  2. Catch the signal using trap and take appropriate action.
  3. Take the default action.

All the above is true except for the following signals:

SIGKILL (signal 9)

SIGSTOP (signal 17)

SIGCONT (signal 19)

These cannot be caught and always uses the default action.



Signal Syntax

trap [ command ] signal [ signal ... ]

  • Command can be explicit commands or a function
    • Command
      trap 'echo signal received, now exiting..; exit' 2 6
      
    • function
      function mysignal {
          echo "in mysignal function"
          exit
      }
      trap 'mysignal' 2 6
      
  • Signal can be a signal number or signal name

  Signals numbers from 0 to 31, "0" being a pseudo-signal meaning "program termination", or using name, HUP for HANGUP signal, TERM for the SIGTERM signal etc.

trap 'echo signal received, now exiting..; exit' 2 6
trap 'echo signal received, now exiting..; exit' SIGINT SIGQUIT


What will script do when a signal(for example 15) is received:

  1. The script would trap the signal 15, and execute the command "rm -f $Tmp", thus removing the temporary file.
  2. it would continue with the next script command. This could cause strange results, because the (probably needed) temporary file $Tmp is gone. Another point is that somebody explicitly tried to terminate the script, a fact it deliberately ignores.

How to ignore and reset default signal handler


To ignore a signal, use two single quotes in place of the command:

trap ''  signals

To reset a trap use:

trap -  signals


KSH Signal Code Samples


 1  #!/bin/ksh
 2
 3  function mysignal {
 4          echo "in mysignal"
 5          #exit
 6  }
 7
 8  trap "mysignal" SIGINT SIGQUIT
 9
10  function mainfun {
11          sleep 10
12  }
13
14  mainfun
15
16  echo "End of script"


When script is running, and CTRL-2 is pressed, function mysignal will be called, and after function is finished, control-flow come to the statement immediately after 'mainfun', so the final "End of script" is executed.

So if line 5 (#exit) is not commented out, line 16 will not be executed, because script will exit at line 5.


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值