dqqlziv195281 2010-12-12 21:54
浏览 125

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

Here's very simple program that I am testing on

#!/usr/bin/perl

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

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

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

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

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

print "Script Testing Done
";

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 and change those script and direct the output to a file where php/ajax can get the content and output to the browser.

Thanks

  • 写回答

3条回答

  • donglilian0061 2010-12-12 21:59
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示