我正在使用 pdftk 合并 pdf 文件。有时,用户上传格式不正确的 pdf,它会挂起进程,不返回任何错误并消耗所有服务器资源。为了防止这种情况发生,我正在考虑实现进程调用,proc_open并希望为进程设置运行时间限制,如果超过时间限制则终止进程。
下面是我用来合并 pdf 文件的函数示例,如果我设置
stream_set_blocking($process, 0);
它返回一个错误:
stream_set_blocking(): supplied resource is not a valid stream resource
我认为此函数中的某些内容格式不正确,希望有人能够为我指出正确的方向...该函数目前没有返回任何错误,但不会根据需要在 30 秒后终止
 protected function pdf_merge($documents,$output_file,$time = 30){      
        $end = time() + $time;
        $cmd = sprintf('/usr/local/bin/pdftk %s cat output %s', $documents, $output_file);
        $descriptorspec = array(
           0 => array("pipe", "r"),  
           1 => array("pipe", "w"),  
           2 => array("file","./error.log","a")
        );
        $process = proc_open($cmd, $descriptorspec, $pipes);
        if (is_resource($process)) {
            stream_set_blocking($pipes[1], 0);
            while (!feof($pipes[1]) && (time() < $end)) {
                fwrite($pipes[0], stream_get_contents($pipes[0]));
                fclose($pipes[0]);
                $pdf_content = stream_get_contents($pipes[1]);
                fclose($pipes[1]);
                $return_value = proc_close($process);
                return $return_value;
            }   
            error_log('file is taking too long... kill process');
            proc_terminate();               
        }
    }