svsem/event_flags.c

This is svsem/event_flags.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 47-5:a (page 995).

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU Lesser 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 svsem/event_flags.c

  Cover of The Linux Programming Interface

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

/* event_flags.c

   Implement an event flags protocol using System V semaphores.

   See event_flags.h for a summary of the interface.
*/
#include <sys/types.h>
#include <sys/sem.h>
#include "semun.h"              /* Definition of semun union */
#include "event_flags.h"
#include "tlpi_hdr.h"
/* Wait for the specified flag to become "set" (0) */

int
waitForEventFlag(int semId, int semNum)
{
    struct sembuf sops;

    sops.sem_num = semNum;
    sops.sem_op = 0;                    /* Wait for semaphore to equal 0 */
    sops.sem_flg = 0;

    /* Waiting for a semaphore to become zero may block, so we
       program to retry if interrupted by a signal handler */

    while (semop(semId, &sops, 1) == -1)
        if (errno != EINTR)
            return -1;
    return 0;
}
/* "Clear" the event flag (give it the value 1) */

int
clearEventFlag(int semId, int semNum)
{
    union semun arg;

    arg.val = 1;
    return semctl(semId, semNum, SETVAL, arg);
}
/* "Set" the event flag (give it the value 0) */

int
setEventFlag(int semId, int semNum)
{
    union semun arg;

    arg.val = 0;
    return semctl(semId, semNum, SETVAL, arg);
}
/* Get current state of event flag */

int
getFlagState(int semId, int semNum, Boolean *isSet)
{
    union semun dummy;

    int sem_val = semctl(semId, semNum, GETVAL, dummy);
    if (sem_val == -1)
        return -1;

    *isSet = (sem_val == 0) ? TRUE : FALSE;
    return 0;
}

 

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