Perl CGI. no output until backend script is done

It is a basic Perl CGI question, I want to print out "Processing ... " while backend script /script/wait.pl is still running.

But acctually, nothing appeared in browser untill /script/wait.pl finished.

 
print "Content-type:text/html\r\n\r\n";
print '<html>';
print '<head>';
print '</head>';
print '<body>';
print '<h2>Processing ... </h2>';
`/script/wait.pl`;
print '</body>';
print '</html>';

Perl buffers output on stdout by default untill the buffer is full, or a newline is found. You can force output either by adding ',"\n"' to the end of your print statements, or by disabling output buffering by adding this line near the top:

$| = 1;

But even then it's not guaranteed that the browser will start rendering the page before it received all the content.

Hi,
It should print..What is the contents of wait.pl? Do you see anything in the error_log of your webserver?

-Raja

$| doesn't work, To make it simple, I tested following script. I expect "OK, starting time consuming process " appeared first, then "All done" aftter 5 seconds. But they all appeared all together after 5 secs.

BTW: I use apache2 with mod_perl2

#!/usr/bin/perl -wT

use strict;
$| = 1;

print "Content-type: text/plain\n\n";

print "OK, starting time consuming process ... \n";


for ( my $loop = 1; $loop <= 5; $loop++ ) {
    print "Iteration: $loop\n";
    ## Perform some time consuming task here ##
    sleep 1;
}
print "All Done!\n";

I found two solutions for the issue.

Solution #1

#!/usr/bin/perl -w
use CGI qw(:standard);
$|=1;
my $r = shift;
print header('text/html');
print start_html;
$r->print ("Processing ... <br>");
foreach $i (1..2) {
    sleep 2;
   $r->print ("Item .. $i <br>");
}
$r->print ("DONE <br>");
print end_html;

Solution #2

 
#!/usr/bin/perl -w
use CGI qw(:standard);
my $r = shift;
print header('text/html');
print start_html;
print br ("Processing ... ");
 $r->rflush;
foreach $i (1..2) {
    sleep 2;
    print br  ("Item .. $i ");
    $r->rflush;
}
print br ("DONE");
print end_html;
 

For more information, please check my post
http://honglus.blogspot.com/2010/08/resolving-perl-cgi-buffering-issue.html