Linux【9】-进程管理4-5--时间控制--timeout

有些shell脚本或者命令,只有在规定时间内运行完成才有意义,这时可以设置脚本/命令的时间限制,如果在设定时间内,还没有完成,则终止命令/脚本。可以使用timeout命令来做到,先看一下它的用法:

二、用法示例

2.1 示例1

假设有如下脚本,每隔一秒钟输出一次系统时间

qingsong@db2a:~$ cat infiniteloop.sh

#!/bin/bash
while true
do
    echo -n "Current date: "
    date
    sleep 1
done

qingsong@db2a:~$ bash infiniteloop.sh

Current date: Thu Aug 17 02:48:15 PDT 2017
Current date: Thu Aug 17 02:48:16 PDT 2017
Current date: Thu Aug 17 02:48:17 PDT 2017
Current date: Thu Aug 17 02:48:18 PDT 2017
Current date: Thu Aug 17 02:48:19 PDT 2017
Current date: Thu Aug 17 02:48:20 PDT 2017
Current date: Thu Aug 17 02:48:21 PDT 2017
Current date: Thu Aug 17 02:48:22 PDT 2017
Current date: Thu Aug 17 02:48:23 PDT 2017
^C <---Ctrl+c手动终止

可以看到,上面的脚本只有ctrl+c才会终止,否则会永远运行,现在可以使用timeout,设置超时限制为3秒钟:

qingsong@db2a:~$ timeout 3 bash infiniteloop.sh 
Current date: Thu Aug 17 02:48:35 PDT 2017
Current date: Thu Aug 17 02:48:36 PDT 2017
Current date: Thu Aug 17 02:48:37 PDT 2017
qingsong@db2a:~$ 

2.2 示例2

timeout命令还可以发送信号,具体怎么处理信号,由程序或者shell本身决定。下面的脚本中,对于SIGINT信号的处理方式仅仅是打印一条信息

qingsong@db2a:~$ cat infiniteloop.sh

#!/bin/bash

trap "echo received a interrupt signal" SIGINT

while true
    do
    echo -n "Current date: "
    date
    sleep 1
done

timeout命令在3s后向脚本发出一个SIGINT信号:

qingsong@db2a:~$ timeout -s SIGINT 3 bash infiniteloop.sh

Current date: Thu Aug 17 03:41:09 PDT 2017
Current date: Thu Aug 17 03:41:10 PDT 2017
Current date: Thu Aug 17 03:41:11 PDT 2017
received a interrupt signal <--捕捉到由timeout发出的信号
Current date: Thu Aug 17 03:41:12 PDT 2017
Current date: Thu Aug 17 03:41:13 PDT 2017
Current date: Thu Aug 17 03:41:14 PDT 2017
^Creceived a interrupt signal <---Ctrl+c手动终止
Current date: Thu Aug 17 03:41:14 PDT 2017
Current date: Thu Aug 17 03:41:15 PDT 2017
^Creceived a interrupt signal <---Ctrl+c手动终止
Current date: Thu Aug 17 03:41:16 PDT 2017
Current date: Thu Aug 17 03:41:17 PDT 2017
^Z <--手动地ctrl+z
[1]+ Stopped timeout -s SIGINT 3 bash infiniteloop.sh

qingsong@db2a:~$ jobs

[1]+ Stopped timeout -s SIGINT 3 bash infiniteloop.sh

qingsong@db2a:~$ ps -ef | grep -i infiniteloop.sh 

qingsong 52631 46284 0 03:41 pts/5 00:00:00 timeout -s SIGINT 3 bash infiniteloop.sh
qingsong 52632 52631 0 03:41 pts/5 00:00:00 bash infiniteloop.sh
qingsong 52690 46284 0 03:41 pts/5 00:00:00 grep --color=auto -i infiniteloop.sh

qingsong@db2a:~$ kill -9 52631

参考资料

这里是一个广告位,,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn