How mkstemp() actually works?

Solution 1:

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

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.