This is fileio/atomic_append.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is the solution to Exercise 5-3 (page 110).

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.


Download fileio/atomic_append.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* atomic_append.c

   Demonstrate the difference between using nonatomic lseek()+write()
   and O_APPEND when writing to a file.

   Usage: file num-bytes [x]

   The program write 'num-bytes' bytes to 'file' a byte at a time. If
   no additional command-line argument is supplied, the program opens the
   file with the O_APPEND flag. If a command-line argument is supplied, the
   O_APPEND is omitted when calling open(), and the program calls lseek()
   to seek to the end of the file before calling write(). This latter
   technique is vulnerable to a race condition, where data is lost because
   the lseek() + write() steps are not atomic. This can be demonstrated
   by looking at the size of the files produced by these two commands:

        atomic_append f1 1000000 & atomic_append f1 1000000

        atomic_append f2 1000000 x & atomic_append f2 1000000 x
#include <sys/stat.h>
#include <fcntl.h>
#include <stdbool.h>
#include "tlpi_hdr.h"
main(int argc, char *argv[])
    if (argc < 3 || strcmp(argv[1], "--help") == 0)
        usageErr("%s file num-bytes [x]\n"
                 "        'x' means use lseek() instead of O_APPEND\n",

    bool useLseek = argc > 3;
    int flags = useLseek ? 0 : O_APPEND;
    int numBytes = getInt(argv[2], 0, "num-bytes");

    int fd = open(argv[1], O_RDWR | O_CREAT | flags, S_IRUSR | S_IWUSR);
    if (fd == -1)

    for (int j = 0; j < numBytes; j++) {
        if (useLseek)
            if (lseek(fd, 0, SEEK_END) == -1)
        if (write(fd, "x", 1) != 1)
            fatal("write() failed");

    printf("%ld done\n", (long) getpid());


Download fileio/atomic_append.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1