linux设置程序运行超时时间

在某些状况下,咱们须要限制程序的运行时间(好比cronjob等),这里简单介绍下使用信号及timeout的实现方法bash

1. 假若有以下代码(test_timout.sh):spa

#!/bin/bash

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

一旦运行后(bash test_timout.sh),就没法自行终止;若是在代码中有bug,致使程序没法正常终止,那么机器的资源就得不到释放(若是是cronjob的话,资源占用就会愈来愈多),所以在这种状况下,咱们须要设置程序的运行时间;经过信号和timeout命令的实现以下blog

2. 让上面的代码在3秒后字段退出的解决方案以下:资源

   1)修改上面的代码(test_timout.sh),使其能在捕捉信号后退出it

#!/bin/bash

trap "echo received a interrupt signal; exit 1" SIGINT 
while true
    do
    echo -n "Current date: "
    date
    sleep 1
done

  2)运行命令由bash test_timout.sh改成timeout -s SIGINT 3 bash test_timout.sh;这样在3秒后,程序就会自动退出class

相关文章
相关标签/搜索