- 這種方法只能用在cli下, apache,(f)cgi 下使用可能會出現難料的結果
- 沒看過別人用這招,考靠度未經驗證,所以有支援timeout的function還是用他內建的為先
- 測試過後還是有些function不吃這招(只好再想別的方法中斷他)
declare(ticks = 1);
function throw_exception($signal) {
pcntl_signal(SIGALRM, SIG_IGN);
throw new Exception('throw_exception');
}
pcntl_signal(SIGALRM, "throw_exception", false);
pcntl_alarm(1);
$connect_timeout = false;
try{
$data = file_get_contents('http://1.1.1.1');
pcntl_signal(SIGALRM, SIG_IGN);
}catch(Exception $e){
$connect_timeout = true;
}
if($connect_timeout){
echo "timeout!\n";
}else{
echo "ok got data:".$data."\n";
}
?>