[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Puzzle - Temp file creation



On Wed, Jul 14, 1999 at 12:33:49PM -0500, Tom Rowton wrote:
> <unlurk>
> wouldn't it be more reliable - for finding a temp filename - to use
> something like
> time() to get an almost definitely unique filename? or did I get lost in all
> the subthreads?
> 
> i can see how all this is intellectually fun, but if I need a unique,
> non-used filename, there is no way on earth that another file on my system
> has the same filename if I append a unix time to the end of it. maybe I
> missed the point.
> </unlurk>

In the computer world, a second is a very long time.

Say you have a program that does:

open(TMP, ">foo".time);

And several copies of that program are running at the same time (say
its a CGI program on a high-load web server).  What happens when two
of them get run in the same second?  Ooops.

open(TMP, ">foo".time.$$"); isn't even safe, because if your program
is running persistantly (say as a daemon or under mod_perl or FastCGI)
subsequent runs will have the same PID, and if it runs twice in the
same second (a strong possibility), you're screwed.


Has anyone brought up perlfaq5: "How do I make a temporary file name?" yet?

use Fcntl;
use POSIX qw(tmpnam);

do { $name = tmpnam() }
	until sysopen(FH, $name, O_RDWR|O_CREAT|O_EXCL);

or

use IO::File;
$fh = IO::File->new_tmpfile()
	or die "Unable to make new temporary file: $!";

-- 

Michael G Schwern                                           schwern@pobox.com
                    http://www.pobox.com/~schwern
     /(?:(?:(1)[.-]?)?\(?(\d{3})\)?[.-]?)?(\d{3})[.-]?(\d{4})(x\d+)?/i


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe