A small snippet on how to create a unique filename in a directory possibly shared over the network between several processes.
This code protects your code against unvoluntarily creating two (temporary) files that get the same name. It does not shield you from malicious race conditions, like another program explicitly creating a file with the same name you chose.
We use the following items to ensure uniqueness down to the level of one second. This means that, unless your machine reissues the same process ID within 1 second, the code will return unique filenames.
Update :In another post by ybiC, I saw the mention of Sys::HostIP, which tries harder than Sys::Hostname to find the hostname of a machine. So maybe it would be useful in this snippet, but it is not in the Perl standard distribution.
A one liner :A function :perl -MSys::Hostname -we 'print( hostname() . ".$$." . time() . ".tmp" +, "\n")'
require Sys::Hostname; sub uniqueFilename() { my $processName; $processName = shift || "tmp"; return $processName . "." . hostname() . ".$$." . time() . ".tmp"; };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Unique filenames in a shared directory (The Kitchensink)
by repson (Chaplain) on Dec 05, 2000 at 08:06 UTC |