PHP Multiprocessing Inter-Process Communication


Interprocess communication allows programmers to communicate between different processes. For example let us consider we need to write an PHP application that can run bash commands and print the output. We will be using proc_open , which will execute the command and return a resource that we can communicate with. The following code shows a basic implementation that runs pwd in bash from php

    $descriptor = array(
        0 => array("pipe", "r"), // pipe for stdin of child
        1 => array("pipe", "w"), // pipe for stdout of child
    $process = proc_open("bash", $descriptor, $pipes);
    if (is_resource($process)) {
        fwrite($pipes[0], "pwd" . "\n");
        echo stream_get_contents($pipes[1]);
        $return_value = proc_close($process);


proc_open runs bash command with $descriptor as descriptor specifications. After that we use is_resource to validate the process. Once done we can start interacting with the child process using $pipes which is generated according to descriptor specifications.

After that we can simply use fwrite to write to stdin of child process. In this case pwd followed by carriage return. Finally stream_get_contents is used to read stdout of child process.

Always remember to close the child process by using proc_close() which will terminate the child and return the exit status code.