开发者

Displaying Console Ouput in Browser while the Perl Script is still running

Here's very simple program that I am testing on

#!/usr/bin/perl

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "This is Test Script\n";
sleep(5);

print "Script Testing Done\n";

Now PHP should output the script output (which is going to console) every maybe 10 seconds or 5 seconds or whenever the php sees the output on the console.

I have hundreds of perl scripts and I cannot go 开发者_C百科and change those script and direct the output to a file where php/ajax can get the content and output to the browser.

Thanks


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)\n";
        $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


I might be barking up the wrong tree here, but isn't it possible that you are Suffering from Buffering?


Um, back in the old days I'd use CGI with non-parsed headers (NPH... google it) and $|=1 "when you want your pipes to be piping hot".

You're going to have to do something similar with the PHP side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜