You probably want proc_open()
and flush()
.
The former allows you to read/write to processes at will. The latter flushes the output buffer.
(Edit, add example code)
Here is a sample PHP script that invokes your Perl sample above (assuming its called test.pl
). Note that due to Perl's output buffering mechanism, you need to tell your Perl script to make STDOUT implicitly flush (or "make it hot" in Perl-speak). You can do this by adding $|=1
at the top of your Perl script.
<?php
$descriptor = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w"), // stderr
);
$proc = proc_open('./test.pl', $descriptor, $pipes);
if ($proc) {
fclose($pipes[0]); // no input
stream_set_blocking($pipes[1], 0); // turn off blocking
while (!feof($pipes[1])) {
echo "PHP> (heartbeat)
";
$fromPerl = fread($pipes[1], 1024); // read up to 1k
if ($fromPerl) {
echo "Perl> {$fromPerl}";
}
sleep(2); // do other work instead
}
proc_close($proc);
}
Here is the output:
$ time php proc.php
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
PHP> (heartbeat)
Perl> This is Test Script
PHP> (heartbeat)
PHP> (heartbeat)
Perl> Script Testing Done
PHP> (heartbeat)
real 0m30.031s
user 0m0.020s
sys 0m0.018s