相当于PHP中的子流程吗

相当于PHP中的子流程吗

本文介绍了相当于PHP中的子流程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java和Python中,您具有 ProcessBuilder 子进程模块,使您可以轻松地使用未转义的字符串启动进程,例如 ["ls",一些未转义的目录名称"] -它们还为您提供了强大的工具,例如可以从stdout,stderr读取内容.是否有PHP的等效功能比 exec()更智能和有用?

In Java and Python, you have the ProcessBuilder or subprocess modules that let you easily start a process using unescaped strings e.g. ["ls", "some unescaped directory name"] - they also give you powerful tools like access to read from stdout, stderr. Is there any equivalent feature of PHP that is more intelligent and useful than just exec()?

推荐答案

最接近的等效项,使您可以访问 stdin stdout stderr proc_open() .

The closest equivalent that gives you access to stdin, stdout, and stderr, with two-way communication, would be proc_open().

这是文档中的示例:

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

如果只需要 stdout stdin ,则可以使用 popen() .

If you only need stdout and stdin, you can use popen().

这是我的修改示例,因为手册很烂:

This is my modified example, since the manual's sucks:

<?php
$handle = popen('/path/to/executable', 'r');

$lines = [];
while (!feof($handle))
{
    $lines[] = fgets($handle);
}

pclose($handle);

这会将/path/to/executable 的输出读取到输出行数组中.

This will read the output of /path/to/executable into an array of lines of output.

您还询问了转义参数.您可以使用 escapeshellarg() 来做到这一点:

You also asked about escaping arguments. You can do that with escapeshellarg():

$escapedArg = escapeshellarg($arg);

这篇关于相当于PHP中的子流程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 05:43