ksh trap signal

来源:互联网 发布:Excel数据有效性底纹 编辑:程序博客网 时间:2024/05/10 22:18


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 6trap '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 910  function mainfun {11          sleep 1012  }1314  mainfun1516  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
原创粉丝点击