If you've ever needed to add a CGI interaface to a long running process, you probabaly know that if you don't provide the browser with periodic "feedback", it will time out and the user will never see the result. The code below solves this by forking and having the parent send back NULLs (\0) to the browser until the child process completes. There's nothing magic about Null except that it's doesn't display. If you want a "progress indicator" effect, you could replace them with "*" or whatever you like (though some browsers may not display them until the script completes).
Update: The code below turned out to be responsible for some strangeness in Apache under rare circumstances, yet I could never find the real root of it nor a fix. Another solution involving alarms was deployed and has worked consistantly without problem, I'll post that whenever I find the time.
#!/usr/bin/perl -w
use strict;
use POSIX;
# incomplete example, tailor to you needs
$| = 1;
my $pid = fork;
my $result;
if ($pid) {
my $kid;
print "Please Wait...<br>\n";
do {
sleep 2;
print "\0";
$kid = waitpid(-1, &WNOHANG);
if ($kid > 0) {
$result = $? >> 8;
}
} until ($kid == -1);
} else {
if (defined $pid) {
exec("./long_running_prog");
CORE::exit 1;
} else {
print "Failed to fork!<br>";
$result = 1;
}
}
if (not $result) {
print "Run successful<br>\n";
} else {
print "Run Failed. Error($result)<br>\n";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.