TIL: Atomically check existence for file and create if it does not exist

2023-02-19 00:00:00 +0000 UTC

A quick-and-dirty way to lock a directory in a Linux C program is to create a specific file in that directory. However, it is easy to accidentally create a race condition. The correct way to use this technique is to use the system call open.

The function prototype for open is:

int open(const char *pathname, int flags);

The two relevant values for flags are O_CREAT and O_EXCL. A call to open that atomically checks for the existence of a file and creates it if it does not exist is:

open(p, O_CREAT | O_EXCL);

This creates a file at path p if the file does not exist. If the file at path p does exist, the return value of open is EEXIST.

Tags: c til