This is fileio/multi_descriptors.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-6 (page 111).

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/multi_descriptors.c

  Cover of The Linux Programming Interface

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

/* multi_descriptors.c

   Show the interaction of multiple descriptors accessing the same
   file (some via the same shared open file table entry).
#include <sys/stat.h>
#include <fcntl.h>
#include "tlpi_hdr.h"
main(int argc, char *argv[])
    int fd1, fd2, fd3;
#define file "a"
    char cmd[] = "cat " file "; echo";

    fd1 = open(file, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd1 == -1)
        errExit("open fd1");
    fd2 = dup(fd1);
    if (fd2 == -1)
    fd3 = open(file, O_RDWR);
    if (fd3 == -1)
        errExit("open fd3");

    /* 'fd1' and 'fd2' share same open file table entry (and thus file
       offset). 'fd3' has its own open file table entry, and thus a
       separate file offset. */

    if (write(fd1, "Hello,", 6) == -1)
    if (write(fd2, " world", 6) == -1)
    if (lseek(fd2, 0, SEEK_SET) == -1)
    if (write(fd1, "HELLO,", 6) == -1)
    if (write(fd3, "Gidday", 6) == -1)

    if (close(fd1) == -1)
        errExit("close output");
    if (close(fd2) == -1)
        errExit("close output");
    if (close(fd3) == -1)
        errExit("close output");


Download fileio/multi_descriptors.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