zoukankan      html  css  js  c++  java
  • #每日Linux小练习#09 trap指令

    在有些情况下,我们不希望自己的shell脚本在运行时刻被中断,比如说我们写得shell脚本设为某一用户的默认shell,使这一用户进入系统后只能作某一项工作,如数据库备份, 我们可不希望用户使用ctrl+C之类便进入到shell状态,做我们不希望做的事情。这便用到了信号处理。 

    trap命令用来指定shell需要捕捉哪些Linux信号,以及如何处理这些信号。格式如下:

    trap commands signals

    不同的signal之间用空格隔开,commands表示如何处理signals。

    echo trap "echo sorry, I have trapped Ctrl-C" SIGINT SIGTERM
    trap "echo sorry, I have trapped Ctrl-C" SIGINT SIGTERM
    echo "Running..."
    
    count=1
    while [ $count -le 5 ]
    do
        echo "Loop  $count"
        count=$(($count + 1))
        sleep 2
    done
    
    echo trap - SIGINT SIGTERM
    trap - SIGINT SIGTERM   #移除捕捉
    
    echo "Ending..."

    上述脚本在每次检测到SIGINT或者SIGTERM信号时,简单地显示一行信息,然后继续向下执行,而并不会终止程序。

    如果trap命令的signals部分变为”EXIT”会如何呢?此时无论脚本是否正常退出,shell都会在程序终止时执行commands部分: 

    echo " "
    echo trap "echo this loop ends" EXIT
    trap "echo this loop ends" EXIT
    echo "Running..."
    
    count=1
    while [ $count -le 5 ]
    do
        echo "Loop  $count"
        count=$(($count + 1))
        sleep 2
    done
    
    echo "Ending..."

    本文中代码可以从github上面下载,https://github.com/yifeng152/oneShellPracticePerDay.git

    对应文件为20150811trap.sh

    参考链接:

    http://blog.sina.com.cn/s/blog_460757d50100v0ox.html
    http://www.cnblogs.com/benxintuzi/p/4720647.html

  • 相关阅读:
    iOS软件版本更新思路
    Xcode里-ObjC, -all_load, -force_load
    NSFileManager
    [Android问答] px、dp和sp,这些单位有什么区别?
    annot refer to a non-final variable * inside an inner class defined in a different method"错误解析
    android Handler post sendMessage
    谈layout_gravity和gravity的用法
    Android LayoutInflater详解
    Android中pendingIntent的深入理解
    Intent和PendingIntent的区别
  • 原文地址:https://www.cnblogs.com/wuqi/p/4725930.html
Copyright © 2011-2022 走看看