[Insight-developers] portable temporary file name generator function?

kent williams norman-k-williams at uiowa.edu
Wed Jul 29 17:48:50 EDT 2009


Yeah, you found the conundrum.  If you can't come up with a temporary name
and create the file in one atomic operation, you're theoretically up against
a race condition -- another process could create that file between choosing
the filename and opening it.

My 'solution' is robust enough for our purposes, though it's neither
thread-safe nor secure. It also does nothing to check for things like /tmp
filling up or being unwritable. And it will fail on Windows as it stands
unless you've made a '/tmp' directory on every drive. But I will worry about
that if we ever deploy on Windows.

namespace {

  vnl_random randgen;
  bool randomized(false);
  // TODO
std::string NewTempName()
{
#if !defined(_WIN32)
  if(!randomized)
    {
    randomized = true;
    randgen.reseed(static_cast<unsigned long>(getpid()));
    }
#endif
  // it needs to be an image name. None of the standard library functions I
know
  // about generate unique filenames with suffixes.
  for(;;)
    {
    std::ostringstream strvalue;
    strvalue << "/tmp/";
    strvalue << randgen.lrand32();
    strvalue << randgen.lrand32();
    strvalue << ".nii.gz";
    if(!vtksys::SystemTools::FileExists(strvalue.str().c_str(),true))
      {
      return strvalue.str().c_str();
      }
    }
}


On 7/29/09 4:26 PM, "Mathieu Malaterre" <mathieu.malaterre at gmail.com> wrote:

> On Tue, Jul 28, 2009 at 8:46 PM, kent
> williams<norman-k-williams at uiowa.edu> wrote:
>> I have need to generate some temporary filenames, in order to write out
>> images for external programs to use as inputs.
>> 
>> I notice there's no temporary file name generator in itksys::SystemTools.
>> 
>> Shouldn't there be?
>> 
>> I'd can write one, no doubt, but don't have Windows builds to test it on.
>> 
>> Is there one buried somewhere in CMake?
> 
> The only one I found out to be working on linux and win32 was tempnam:
> 
>  char *tempnam(const char *dir, const char *pfx);
> 
> Most documentation will tell you this is a bad idea anyway and should
> instead request a file (without knowing the actual filename) from the
> system (eg: tmpfile).
> 
> 
> HTH



More information about the Insight-developers mailing list