linux设置程序运行超时时间

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

1. 假如有如下代码(test_timout.sh):

#!/bin/bash

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

一旦运行后(bash test_timout.sh),就无法自行终止;如果在代码中有bug,导致程序无法正常终止,那么机器的资源就得不到释放(如果是cronjob的话,资源占用就会越来越多),

因此在这种情况下,我们需要设置程序的运行时间;通过信号和timeout命令的实现如下

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

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

#!/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秒后,程序就会自动退出

猜你喜欢

转载自www.cnblogs.com/276815076/p/10966751.html