wangzhengquan
2020-05-25 ff31a5b78ebe4b4348ed7fd572941b23a87414c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* 
   Implement a binary semaphore protocol using System V semaphores.
*/
#include <sys/types.h>
#include <sys/sem.h>
#include "common.h"
#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;
}
 
int                     /* Release semaphore - increment it by 1 */
releaseSem(int semId, int semNum)
{
    struct sembuf sops;
 
    sops.sem_num = semNum;
    sops.sem_op = 1;
    sops.sem_flg = bsUseSemUndo ? SEM_UNDO : 0;
 
    return semop(semId, &sops, 1);
}