Bugzilla – Bug 14381
tempfile() always returns the same result when run as the first statement after starting R
Last modified: 2010-09-22 08:46:15 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.
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.
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
Changed for R 2.12.0.
Thanks to both Simon and Brian.