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

Does mkstemp open files only if they don't already exist?

On Wed, Sep 2, 2015 at 12:45 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> I assume the answer is "Yes", but is it safe to expect that
> tempfile.mkstemp() will only create a file that doesn't already exist? I
> presume that there's no chance of it over-writing an existing file (say,
> due to a race-condition).

It depends on OS support, but with that, yes, it is guaranteed to be
safe; the file is opened with an exclusivity flag. Check your system's
man pages for details, or here:


O_EXCL|O_CREATE makes an "atomic file creation" operation which will
fail if another process is doing the same thing. I'm not sure how
mkstemp() handles that failure, but my guess/expectation is that it
would pick a different file name and try again.