Function name: proc_open()
Function Description: The proc_open() function executes a command and opens the file pointer used for input/output.
Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7
Syntax: resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env [, array $other_options ]]] )
parameter:
Return value: Returns a process identifier of the resource type when successful, and returns FALSE when failure.
Sample code:
// 执行一个简单的命令并读取输出$descriptorspec = array( 0 => array("pipe", "r"), // 标准输入1 => array("pipe", "w"), // 标准输出2 => array("pipe", "w") // 标准错误); $process = proc_open('ls -l', $descriptorspec, $pipes); if (is_resource($process)) { // 读取输出echo stream_get_contents($pipes[1]); // 关闭文件指针fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); // 等待进程结束,并获取返回值$return_value = proc_close($process); }
In this example, we use proc_open() to execute a simple command "ls -l" and use a file pointer to read the output of the command. By setting the appropriate descriptorspec array, we can specify the file pointer type for input/output. In this example, we redirect the standard input to one pipeline and the standard output and standard error to two other pipelines. We then use the stream_get_contents() function to read the output of the command from the standard output pipeline. Finally, we close all file pointers and use proc_close() to wait for the process to end and get the return value.