Current Location: Home> Function Categories> proc_open

proc_open

Execute a command and open the file pointer used for input/output
Name:proc_open
Category:Program execution
Programming Language:php
One-line Description:Execute a command and open the file pointer used for input/output

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:

  • cmd: The command to be executed can be a simple command or an array containing commands and parameters.
  • descriptorspec: an array containing file pointers for input/output. Each element is an array containing the following key values:
    • 0: Standard input (stdin)
    • 1: Standard output (stdout)
    • 2: Standard error (stderr)
  • pipes: will store arrays of all file pointers for input/output
  • cwd (optional): The current working directory in which the command is to be executed
  • env (optional): an array used to set environment variables
  • other_options (optional): An associative array containing additional options. Supported options are:
    • suppress_errors: Disables sending error output to standard error streams. Default is false.

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.

Similar Functions
Popular Articles