在某些情况下,我们需要限制程序的运行时间(比如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秒后,程序就会自动退出

相关文章:

  • 2021-11-16
  • 2022-01-12
  • 2021-12-19
  • 2022-02-03
  • 2021-10-05
  • 2021-08-19
  • 2022-02-27
  • 2022-12-23
猜你喜欢
  • 2021-09-02
  • 2022-12-23
  • 2022-12-23
  • 2022-01-29
  • 2022-12-23
  • 2022-01-18
相关资源
相似解决方案