Connect process pipes in php

I would like the result of one process created with proc_open to be transferred to another created using proc_open (in php). For instance. In bash, I can do:

[herbert@thdev1 ~]$ cat foo
2
3
1
[herbert@thdev1 ~]$ cat foo | sort
1
2
3
[herbert@thdev1 ~]$ 

I would like to simulate this in php using proc_open (instead of shell_exec) in order to have control over returned codes, pipes, etc. So I need something like this:

$catPipes=array();
$sortPipes=array();
$cwd = '/tmp';
$env = array();
$catProcess = proc_open("cat foo", array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w")
    ), $catPipes, $cwd, $env);

$sortProcess = proc_open("sort", array(
    0 => array("pipe", "r", $catPipes[1]),
    1 => array("pipe", "w"),
    ), $sortPipes, $cwd, $env);

echo stream_get_contents($sortPipes[1]);
fclose($sortPipes[1]);
//proc_close(this) ... proc_close(that) ... etc

Does anyone know how I can simulate "|" from bash to php i.e. to connect the second descriptor of the cat process to the first descriptor of the sorting process? Any help would be appreciated! But please don't redirect me to shell_exec as I want to check exit codes and log errors :).

EDIT:

My business solution for business business:

while(!feof($searchPipes[1])) fwrite($lookupPipes[0], stream_get_line($searchPipes[1], 40000));

, , , โ€‹โ€‹/posix , , 1976:)

+2
1

, - , . STDIN "" STDOUT "cat". , :

<?php

$txt = "a\nc\ne\nb\nd\n";
$fh  = fopen('data://text/plain;base64,' . base64_encode($txt), 'r');

$sort_pipes = array();
$sort_proc  = proc_open(
    'sort',
    array(
        array('pipe', 'r'),
        STDOUT
    ),
    $sort_pipes
);

$cat_pipes = array();
$cat_proc  = proc_open(
    'cat',
    array(
        $fh,
        $sort_pipes[0]
    ),
    $cat_pipes
);

, - . , , (a, c, e, b, d). script STDOUT.

, . , :

STDOUT

array(STDOUT)

.

Btw: , . proc_open http://en.php.net/manual/de/function.proc-open.php

: "cat" STDOUT array('pipe', 'w') $cat_pipes[1] STDIN "sort".:)

+2

Source: https://habr.com/ru/post/1676490/


All Articles