【问题标题】:Terminating proc_open after x Secondsx 秒后终止 proc_open
【发布时间】:2012-11-23 01:15:40
【问题描述】:

我正在使用 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();               
        }
    }

【问题讨论】:

标签: php process exec pdftk proc-open


【解决方案1】:

也许我在这里偏离了基地,大部分代码都运行了吗?

fwrite($pipes[0], stream_get_contents($pipes[0]));

看起来您正在尝试将您可以从管道中读取的任何内容写入管道...

此外,您可能需要检查 get_proc_status(),因为在您尝试设置阻塞时该命令可能已经完成...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    相关资源
    最近更新 更多