This is svshm/svshm_xfr_writer.c (Listing 48-2, page 1003), an example from the book, The Linux Programming Interface.

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

This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below.

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 svshm/svshm_xfr_writer.c

  Cover of The Linux Programming Interface

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

#include "semun.h"              /* Definition of semun union */
#include "svshm_xfr.h"
main(int argc, char *argv[])
    int semid, shmid, bytes, xfrs;
    struct shmseg *shmp;
    union semun dummy;

    semid = semget(SEM_KEY, 2, IPC_CREAT | OBJ_PERMS);
    if (semid == -1)

    if (initSemAvailable(semid, WRITE_SEM) == -1)
    if (initSemInUse(semid, READ_SEM) == -1)

    shmid = shmget(SHM_KEY, sizeof(struct shmseg), IPC_CREAT | OBJ_PERMS);
    if (shmid == -1)

    shmp = shmat(shmid, NULL, 0);
    if (shmp == (void *) -1)

    /* Transfer blocks of data from stdin to shared memory */

    for (xfrs = 0, bytes = 0; ; xfrs++, bytes += shmp->cnt) {
        if (reserveSem(semid, WRITE_SEM) == -1)         /* Wait for our turn */

        shmp->cnt = read(STDIN_FILENO, shmp->buf, BUF_SIZE);
        if (shmp->cnt == -1)

        if (releaseSem(semid, READ_SEM) == -1)          /* Give reader a turn */

        /* Have we reached EOF? We test this after giving the reader
           a turn so that it can see the 0 value in shmp->cnt. */

        if (shmp->cnt == 0)

    /* Wait until reader has let us have one more turn. We then know
       reader has finished, and so we can delete the IPC objects. */

    if (reserveSem(semid, WRITE_SEM) == -1)

    if (semctl(semid, 0, IPC_RMID, dummy) == -1)
    if (shmdt(shmp) == -1)
    if (shmctl(shmid, IPC_RMID, 0) == -1)

    fprintf(stderr, "Sent %d bytes (%d xfrs)\n", bytes, xfrs);


Download svshm/svshm_xfr_writer.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