C open with O_EXCL
Create a new file only if its name is still available.
A simple example
open with O_EXCL
- Start with An unused name a.txt
- Do this Create exclusively twice
- Result First succeeds, second fails
Syntax
open(name, creation_flags, 0600)
Run these examples in C
Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonStop two desks claiming the same ticket
Two desks request the same claim number. Use exclusive creation for the second reservation so it cannot replace the first ticket, then report the collision to the clerk.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main(void) {
char ticket[] = "/tmp/claim-XXXXXX";
int first = mkstemp(ticket);
if (first == -1) return 1;
int duplicate = open(ticket, O_WRONLY | O_CREAT | O_EXCL, 0600);
int collision = duplicate == -1 && errno == EEXIST;
if (duplicate != -1) close(duplicate);
close(first);
unlink(ticket);
if (collision) puts("already issued");
return collision ? 0 : 1;
}
already issued
The second reservation identifies the existing name without overwriting its contents.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
What to watch for
These C examples use POSIX file APIs on macOS or Linux. Checking for existence before creation opens a race. Use an atomic create-if-absent operation.