How mkstemp() actually works?

505 Views Asked by At

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

2

There are 2 best solutions below

2
KamilCuk On BEST ANSWER

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.

0
Luis Colorado On

(although chances are very low, but it is possible theoretically)

Nope, it is not possible (even theoretically) as the open() system call that mkstemp() uses to create the file warrants that no two processes can create the same file with O_CREAT and O_EXCL simultaneously. When the kernel creates the file, the directory inode is locked (so, disallowing any other file creation in that directory at the same time), and that warrants that the two open()s will go serialized (one first, or the other, but not both at the same time) This means when the second process has a chance to create the file, the open() call fails because the file has already been created by the other process. To minimize this scenario, the function normally uses the pid of the process as part of the name, so two processes at the same time cannot generate the same filename because they have different process ids) mkstemp() would retry the system call with probably a different name, or just fail.