Bug 14381 - tempfile() always returns the same result when run as the first statement after starting R
tempfile() always returns the same result when run as the first statement aft...
Status: RESOLVED FIXED
Product: R
Classification: Unclassified
Component: I/O
R 2.11.1
Other All
: P5 normal
Assigned To: R-core
Depends on:
Blocks:
  Show dependency treegraph
 
Reported: 2010-09-17 00:33 UTC by Long Qu
Modified: 2010-09-22 08:46 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Long Qu 2010-09-17 00:33:33 UTC
After R starts up, tempfile("",".") as the first command will return the same result each time I start a new R session, which is not expected to me (and very likely other users) as we usually expect something more random than this predictable answer... 

If runif(1) is the first command but the tempfile("",".") is the second, then the results differ each time I re-start R.
Comment 1 Simon Urbanek 2010-09-18 16:01:44 UTC
tempfile() uses rand() and the seed for rand() will not be set unless Randomize() is called (e.g. via GetRNGstate). If an application wants truly random temp file it can call RNGkind() first.

I have added GetRNGstate() to R_tmpnam() to make sure srand() is called. It could be optimized more (by having let's say a global flag) if needed.

Also there is the edge-case of custom RNG hooks which may not trigger srand() call (AFAICS), however, I don't think it would be wise to force srand() in R_tmpnam() directly as that may change the behavior of other code using rand() or RNG.
Comment 2 Brian Ripley 2010-09-22 08:18:11 UTC
This is not normally a problem, as tempfile() is usually used within tempdir()
which does differ by session.

Simon's fix caused other problems, and has been replaced by one in which
srand() is initialized very early in the R session and not as part of the
RNG initialization.

Changed for R 2.12.0.
Comment 3 Long Qu 2010-09-22 08:46:15 UTC
Thanks to both Simon and Brian.