Issue
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
- https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c check input
- https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L229 get some random data
- https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L241 repeat for https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L211 specified number of attempts
- https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L245 fill
XXXXXX
with randoms - https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L261 open file with
O_CREAT | O_EXCL
- https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L293 if the file is opened return, if unknown error return, if the file exists, repeat
- https://github.com/lattera/glibc/blob/master/sysdeps/posix/tempname.c#L245 fill
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.
Answered By - KamilCuk Answer Checked By - David Goodson (WPSolving Volunteer)