PHP proc_open详解

来源:互联网 发布:御姐控 知乎 编辑:程序博客网 时间:2024/05/17 06:43

        php文件的执行,一般都是顺序的。因此当我们的php文件在执行过程中,触发Fatal Error,或者抛出未被捕获的异常时,php文件就会停止执行,因此我们需要使用proc_open函数来分离主脚本和运行脚本。

1.文档实例:

$descriptorspec = array(0 => array("pipe", "r"),//标准输入,子进程从此管道读取数据1 => array("pipe", "w"),//标准输出,子进程向此管道写入数据2 => array("file", "/opt/figli/php/error-output.txt","a")//标准错误,写入到指定文件);$process = proc_open("php", $descriptorspec, $pipes);if(is_resource($process)){fwrite($pipes[0], "<?php echo 'Hello figli!';?>");fclose($pipes[0]);echo stream_get_contents($pipes[1]);fclose($pipes[1]);proc_close($process);//在调用proc_close之前必须关闭所有管道}

2.运行linux命令:

$descriptorspec = array(0 => array("pipe", "r"),//标准输入,子进程从此管道读取数据1 => array("pipe", "w"),//标准输出,子进程向此管道写入数据2 => array("file", "/opt/figli/php/error-output.txt","a")//标准错误,写入到指定文件);$process = proc_open("ls -a", $descriptorspec, $pipes);if(is_resource($process)){echo stream_get_contents($pipes[1]);fclose($pipes[1]);proc_close($process);//在调用proc_close之前必须关闭所有管道}

运行结果:


3.阻塞运行,等待运行结果

$descriptorspec = array(0 => array("pipe", "r"),//标准输入,子进程从此管道读取数据1 => array("pipe", "w"),//标准输出,子进程向此管道写入数据2 => array("file", "/opt/figli/php/error-output.txt","a")//标准错误,写入到指定文件);$process = proc_open("php", $descriptorspec, $pipes);if(is_resource($process)){fwrite($pipes[0], "<?php sleep(5); echo 'Hello figli!';?>");fclose($pipes[0]);echo stream_get_contents($pipes[1]);fclose($pipes[1]);proc_close($process);//在调用proc_close之前必须关闭所有管道}

运行时,php将阻塞直到sleep结束后输出结果。


0 0
原创粉丝点击