The Linux Programming Interface

(nextflipdebug5) #1

990 Chapter 47


Listing 47-10 shows the implementation of the binary semaphore functions. Each
function in this implementation takes two arguments, which identify a semaphore
set and the number of a semaphore within that set. (These functions don’t deal
with the creation and deletion of semaphore sets; nor do they handle the race con-
dition described in Section 47.5.) We employ these functions in the example pro-
grams shown in Section 48.4.

Listing 47-10: Implementing binary semaphores using System V semaphores
–––––––––––––––––––––––––––––––––––––––––––––––––––––– svsem/binary_sems.c
#include <sys/types.h>
#include <sys/sem.h>
#include "semun.h" /* Definition of semun union */
#include "binary_sems.h"

Boolean bsUseSemUndo = FALSE;
Boolean bsRetryOnEintr = TRUE;

int /* Initialize semaphore to 1 (i.e., "available") */
initSemAvailable(int semId, int semNum)
{
union semun arg;

arg.val = 1;
return semctl(semId, semNum, SETVAL, arg);
}

int /* Initialize semaphore to 0 (i.e., "in use") */
initSemInUse(int semId, int semNum)
{
union semun arg;

arg.val = 0;
return semctl(semId, semNum, SETVAL, arg);
}

/* Reserve semaphore (blocking), return 0 on success, or -1 with 'errno'
set to EINTR if operation was interrupted by a signal handler */

int /* Reserve semaphore - decrement it by 1 */
reserveSem(int semId, int semNum)
{
struct sembuf sops;

sops.sem_num = semNum;
sops.sem_op = -1;
sops.sem_flg = bsUseSemUndo? SEM_UNDO : 0;

while (semop(semId, &sops, 1) == -1)
if (errno != EINTR || !bsRetryOnEintr)
return -1;

return 0;
}
Free download pdf