PHP脚本不会死于控制+ c

时间:2016-12-09 10:47:28

标签: php linux wget

我有一个PHP脚本,它使用exec在Linux中启动一些命令。这是一个简单的wget,它会在五分钟后死亡。我面临的问题是,如果我执行Control + c,因为脚本正在运行它不会死,直到我杀死wget的实际PID。我尝试使用pcntl_signal以及使用exec / system / shell_exec等,但没有一个工作。我正在使用的代码是:

<?PHP
system('/usr/bin/timeout 300 wget -c --tries=0 --read-timeout=200 -O /tmp/ll.mp3  http://15323.live.streamtheworld.com:80/WABCAM_SC');  
?>

2 个答案:

答案 0 :(得分:0)

首先,您必须声明ticks directive以使其在PHP 4.3.0及更高版本中运行(请参阅manual page for pcntl_signal)。

然后你必须注册信号和收到信号时调用的回调函数。在您的情况下,您需要按下 CTRL + C 时生成的信号SIGINT

declare(ticks = 1);

// callback function called when signal is received
function shutdown($signal)
{
    echo 'Interrupted using CTRL + C';

    // you probably don't need this condition, just exit should be enough
    if (($signal === SIGINT)) {
        exit;
    }
}

// register the callback function for the specific signal
// SIGINT in this case is generated when you press CTRL + C
pcntl_signal(SIGINT, 'shutdown');

答案 1 :(得分:0)

  

如果我在脚本运行时执行Control + c,它将不会消失

这是因为通过键入中断键从终端生成的信号SIGINT仅发送到终端的前台进程组,并且timeout将自身和给定命令与前台进程隔离通过执行setpgid(0, 0)进行分组。
现在,由于没有将SIGINT发送到timeout命令,因此前台进程将必须处理该信号,并因此杀死timeout命令。正如我们从另一个答案的失败中学到的那样,PHP不太适合这种信号处理,但是我们可以为此使用一些包装器脚本(将其称为timeout.sh

time=$1; shift
timeout $time "$@"&
trap "kill $!" INT
wait $!

<?PHP
system('timeout.sh 300 wget -c --tries=0 --read-timeout=200 -O /tmp/ll.mp3 …');  
?>