1

I have a perl CGI that needs to report some information back to the browser before it goes into a really lengthy process that frequently takes several minutes.

Currently I print the message but it doesn't show up till the entire process exits.

So, my question is:

Is it possible to get the message back to browser mid stream and if not

how do I spawn off a separate process to handle the lengthy bit, so that I can exit out of the initial process and thus have the user get the feedback they need.

The user doesn't need to be notified when the lengthy process is completed, so, I'm fine with quitting as long as the server keeps chugging at it.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
  • 2
    For how to perform background calculations after the CGI process finishes, see http://stackoverflow.com/questions/3440720/interrupted-server-side-perl-cgi-script-when-client-side-browser-closes -- you need a job queue. – Ether Aug 11 '10 at 21:13

1 Answers1

1
# Tell Perl not to buffer our output
$| = 1;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 6
    It should be noted that `$|` is global and will effect all file handles (unrelated file IO). You're almost always better off not doing that... `use IO::Handle; STDOUT->autoflush(1)` instead. – Evan Carroll Aug 11 '10 at 21:20
  • 1
    @Evan "`$|` If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel." I have always assumed that meant `STDOUT` is the one and only handle that will be affected if I do not select some other handle first. – Sinan Ünür Aug 11 '10 at 22:26
  • @Sinan `currently selected output channel` means afaik the one you're outing to, not the one you're providing to `$|`, if `$|` is set to `1`, and you `print $fh "foobar"`, then `$fh` -- the selected output channel will be unbuffered for that call. – Evan Carroll Aug 11 '10 at 22:31
  • I don't like that verbiage: `s/, not the one you're providing to $|//`. – Evan Carroll Aug 11 '10 at 22:43
  • 1
    @Evan If you put it like that, `perldoc -f select` does not make any sense: `$oldfh = select(STDERR); $| = 1; select($oldfh);` to set `$|=1` for `STDERR`. – Sinan Ünür Aug 11 '10 at 22:54
  • 1
    My understanding about the behavior of `$|` is the same as Sinan's, but I agree with Evan that `STDOUT->autoflush(1);` is the better way to set autoflush for STDOUT. – daotoad Aug 12 '10 at 06:31