Cross platform mutex to prevent script running more than instance?

eryk sun eryksun at gmail.com
Thu Sep 6 18:56:57 EDT 2018


On Tue, Sep 4, 2018 at 5:47 PM, Cameron Simpson <cs at cskk.id.au> wrote:
>
> The downside with mkdir, and also with pd files really, is that a program or
> OS abort can leave them lying around. Being persistent objects, some kind of
> cleanup is needed.

While the OP needs a cross-platform solution, if it's just Windows,
the cleanup problem for a temporary directory or lock file can be
handled via the delete-on-close flag. This includes the case in which
the process is forcefully terminated. However, it won't help if the
system itself crashes or gets powered off abruptly.

Details for a directory:

*NT API*
Call NtCreateFile with DELETE access, FILE_CREATE disposition, and the
options FILE_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE.

*Windows API (undocumented)*
Call CreateFile with CREATE_NEW disposition and the attributes/flags
FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_POSIX_SEMANTICS |
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_DELETE_ON_CLOSE.

*Windows API (documented)*
Call CreateDirectory and then CreateFile with OPEN_EXISTING
disposition and the flags FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_DELETE_ON_CLOSE.

*C/POSIX API (undocumented)*
Call os.mkdir and then os.open with the flags O_OBTAIN_DIR (0x2000)
and O_TEMPORARY. (O_OBTAIN_DIR requires the Universal CRT, which is
used by CPython 3.5+.)



More information about the Python-list mailing list