Inter-Process Communication

suggest change

Inter-process communication lets one process talk to another. This example runs pwd in bash and prints the output. proc_open starts the program and returns a process resource. The example needs a bash executable on PATH.

<?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");
        fclose($pipes[0]);
        echo stream_get_contents($pipes[1]);
        fclose($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.

fwrite writes to the child's stdin. Here that is pwd followed by a newline. stream_get_contents reads the child's stdout.

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents