exec() with timeout

后端 未结 7 1066
北荒
北荒 2020-12-03 04:27

I\'m looking for a way to run a PHP process with a timeout. Currently I\'m simply using exec(), but it does not provide a timeout option.

What I also tried is openin

相关标签:
7条回答
  • 2020-12-03 04:56

    Improving on other solutions I came up with this:

    function exec_timeout($cmd,$timeout=60){
            $start=time();
            $outfile=uniqid('/tmp/out',1);
            $pid=trim(shell_exec("$cmd >$outfile 2>&1 & echo $!"));
            if(empty($pid)) return false;
            while(1){
                    if(time()-$start>$timeout){
                            exec("kill -9 $pid",$null);
                            break;
                    }
                    $exists=trim(shell_exec("ps -p $pid -o pid="));
                    if(empty($exists)) break;
                    sleep(1);
            }
            $output=file_get_contents($outfile);
            unlink($outfile);
            return $output;
    }
    
    0 讨论(0)
提交回复
热议问题