I wrote an app similar (actually nearly identical) to this a while back. The approach I took was to have my script check if the item was in the cache, and if not
fork off a process to download the file. Then the main script reads the cache file, and feeds it to the Web browser as it comes in. I used some kind of marker to tell if the file was fully or partially downloaded; I think I used the executable bit and file locks for this.
This solves several problems. First, there's very little latency. Second, it solves the problem of what to do if two browsers try to access the file at once. Third, it solves the problem of what to do if the user presses stop.
Here's some pseudocode, which is probably clearer:
my $url = $cgi->param('url');
my $file = url2file($file);
my $fh = FileHandle->new("< $file");
if ($fh)
{
# Executable means it's a partial download
if (-x F)
{
# If it's not locked, the download process has died
if (flock(F, LOCK_EX|LOCK_NB))
{
$fh=get($file,$url)
or die "Couldn't get URL!\n";
}
stream($fh);
}
stream($fh);
}
else
{
$fh=get($file,$url)
or die "Couldn't get URL!\n";
stream($fh);
}
sub get
{
# Open the filehandle for read and write,
# Lock filehandle for write,
# fork off process to start the download.
# Child Process: Download URL,
# Set +x bit when done
# Return dup of filehandle
}
sub stream
{
# Keep streaming data from filehandle until
# the executable bit is set. Works pretty much like
# tail -f.
}
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.