Library contents

C open with O_EXCL

Create a new file only if its name is still available.

A simple example

open with O_EXCL

  1. Start with An unused name a.txt
  2. Do this Create exclusively twice
  3. Result First succeeds, second fails
The second attempt encounters the file created by the first.

Syntax

C 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
./lesson

Stop 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.

From the programchar ticket[] = "/tmp/claim-XXXXXX"
Resultalready issued
lesson.c
#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;
}
Output
already issued

The second reservation identifies the existing name without overwriting its contents.

Advertisements

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?

GivenFile contents “clay”
Worked resultOriginal kept

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?

GivenFile contents “ring bell”
Worked resultOriginal kept

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.

Documentation for open with O_EXCL