exec() with timeout

后端 未结 7 1064
北荒
北荒 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:47

    (Disclaimer: I was surprised to find no good solution for this, then I browsed the proc documentation and found it pretty straight forward. So here is a simple proc answer, that uses native functions in a way that provides consistent results. You can also still catch the output for logging purposes.)

    The proc line of functions has proc_terminate ( process-handler ), which combined with proc_get_status ( process-handler ) getting the "running" key, you can while loop with sleep to do a synchronous exec call with a timeout.

    So basically:

    $ps = popen('cmd');
    $timeout = 5; //5 seconds
    $starttime = time();
    while(time() < $starttime + $timeout) //until the current time is greater than our start time, plus the timeout
    {
        $status = proc_get_status($ps);
        if($status['running'])
            sleep(1);
        else
            return true; //command completed :)
    }
    
    proc_terminate($ps);
    return false; //command timed out :(
    

提交回复
热议问题