在Perl脚本仍在运行时在浏览器中显示控制台输出

时间:2010-12-12 21:54:05

标签: php perl

这是我正在测试的非常简单的程序

#!/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";

现在PHP应该每隔10秒或5秒输出一次脚本输出(转到控制台),或者每当php看到控制台上的输出时。

我有数百个perl脚本,我不能去更改这些脚本并将输出定向到php / ajax可以获取内容并输出到浏览器的文件。

由于

3 个答案:

答案 0 :(得分:2)

您可能需要proc_open()flush()

前者允许您随意读/写进程。后者刷新输出缓冲区。

(编辑,添加示例代码)

以下是一个示例PHP脚本,它调用上面的Perl示例(假设它名为test.pl)。请注意,由于Perl的输出缓冲机制,您需要告诉Perl脚本使STDOUT隐式刷新(或在Perl-speak中“使其变热”)。您可以通过在Perl脚本的顶部添加$|=1来完成此操作。

<?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);
}

这是输出:

$ 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

答案 1 :(得分:0)

我可能会在这里咆哮错误的树,但你不可能是Suffering from Buffering吗?

答案 2 :(得分:0)

嗯,回到过去我会使用带有非解析标题的CGI(NPH ... google it)和$|=1“当你想让你的管道变热时”。

你将不得不做与PHP方面类似的事情。

相关问题