Search code examples
clinuxposixglibcunistd.h

How mkstemp() actually works?


I am confused regarding the working process of the mkstemp() function.

In the man page of the mkstemp function, it is said that the function generates unique name and create a file with that name.

I think there is possibility that when the mkstemp() checks for that file name in the directory and found it unique before actually creating that file another program can create the file with the exactly the same name (although chances are very low, but it is possible theoretically). Although it will then fail to create the file as it uses O_EXCL flag. So then it have to check again for a new file name and create it. Is this the actual process how mkstemp() works ?

So, I think the checking the file name and creating actually the file , both process it not done atomically. (I may be wrong)

Using aPOSIX system


Solution

  • How mkstemp() actually works?

    Source code is the literal description of an algorithm. Take on one implementation and inspect it.

    https://github.com/lattera/glibc/blob/master/misc/mkstemp.c -> https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c

    So there is no "checking", the file is opened with O_CREAT | O_EXCL from the start, so creating&checking is done together. See https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html for explanation of open flags.