Like @R. that another problem is that, having created the file, there is still a window in front of the contents, such as a mutex, initialized and ready for use.
A slightly different solution above:
Try to open (). If the open () function succeeds, simply match () and use it with the necessary guarantee (see below) that the content is already initialized and it is useful to continue. If open () fails, create and initialize the temporary file, then try the hard link () temporary file as the desired file and cancel () the temporary name.
If link () succeeds, we now make the initialized file available to ourselves and to other processes. If link () fails with EEXIST, another process got there first (unlike rename (), link () fails if target name exists). In any case, our repeated open () should now succeed with the initialized ready-to-use file.
With this strategy, there is clearly a race condition for initializing a temporary file, however, provided that the initialization process is idempotent and not too expensive for resources, and each process selects a unique temporary file, it does not matter. If multiple initialization can be a problem, the solution is to split the initialization into a two-step process, with the first step being just a mutex in the file to use to protect the rest of the file from being multiple-initialized in the second step.
source share