This is svsem/svsem_bad_init.c (Listing 47-5, page 976), 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 svsem/svsem_bad_init.c

  Cover of The Linux Programming Interface

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

/* svsem_bad_init.c

   A demonstration of the wrong way to initialize a system V semaphore.

   Compare this program with svsem_good_init.c.
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include "semun.h"                      /* Definition of semun union */
#include "tlpi_hdr.h"
main(int argc, char *argv[])
    int semid, key, perms;
    struct sembuf sops[2];

    key = 12345;
    perms = S_IRUSR | S_IWUSR;
    semid = semget(key, 1, IPC_CREAT | IPC_EXCL | perms);

    if (semid != -1) {                  /* Successfully created the semaphore */
        union semun arg;

        /* XXXX */

        arg.val = 0;                    /* So initialize it */
        if (semctl(semid, 0, SETVAL, arg) == -1)

    } else {                            /* We didn't create semaphore set */
        if (errno != EEXIST) {          /* Unexpected error from semget() */
            errExit("semget 1");
        } else {                        /* Someone else already created it */
            semid = semget(key, 1, perms);      /* So just get ID */
            if (semid == -1)
                errExit("semget 2");

    /* Now perform some operation on the semaphore */

    sops[0].sem_op = 1;         /* Add 1 */
    sops[0].sem_num = 0;        /* ... to semaphore 0 */
    sops[0].sem_flg = 0;
    if (semop(semid, sops, 1) == -1)



Download svsem/svsem_bad_init.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