陷阱信号和while循环中的清理

时间:2012-05-29 15:22:24

标签: bash

我有这个脚本:

FINISH=0;
trap 'FINISH=1' SIGINT

INTERVAL=100;

while true
do
    START=`date +%s`;
    php-cgi -f process.php;
    STOP=`date +%s`;
    ELAPSED=$(($STOP-$START));
    SLEEP=$(($INTERVAL-$ELAPSED));
    if [ $SLEEP -gt 0 ]
    then
        echo "sleeping for $SLEEP seconds";
        sleep $SLEEP;
    fi
    if [ $FINISH -eq 1 ]
    then
        echo "exit";
        break;
    fi
done

但它不能像我想的那样工作 - 我希望它只设置FINISH = 1但它会杀死当前执行的命令(php-cgi或sleep) - 如何避免这种情况?其实我不希望它杀死php-cgi ...

1 个答案:

答案 0 :(得分:2)

这可能适合你。

#!/bin/bash
trap 'exit' SIGINT

interval=100;

while true
do
    start=$(date +%s)
    nohup php-cgi -f process.php
    stop=$(date +%s)
    ((elapsed = stop - start))
    ((sleep = interval - elapsed))
    if (( sleep > 0 ))
    then
        echo "sleeping for $sleep seconds"
        sleep "$sleep"
    fi
done