-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsem_lock.c
More file actions
135 lines (114 loc) · 1.9 KB
/
sem_lock.c
File metadata and controls
135 lines (114 loc) · 1.9 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include "sem_lock.h"
#include <sys/sem.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <fcntl.h>
int sem_lock_init(sem_lock_t *lock, key_t key)
{
if (lock == NULL)
return -2;
if ((lock->semid = semget(key, 1, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL)) < 0)
{
if (errno == EEXIST)
{
lock->semid = semget(key, 1, S_IRUSR | S_IWUSR);
}
if (lock->semid < 0)
{
perror("semget failed");
return -1;
}
}
union semun un;
un.val = 1;
return semctl(lock->semid, 0, SETVAL, un);
}
int sem_lock_clear(sem_lock_t *lock, int destroy)
{
if (lock == NULL)
return -2;
if (destroy)
return semctl(lock->semid, 0, IPC_RMID);
return 0;
}
static int sem_lock_op(sem_lock_t *lock, short op, short flg)
{
if (lock == NULL)
return -2;
struct sembuf opbuf[1];
opbuf[0].sem_num = 0;
opbuf[0].sem_op = op;
opbuf[0].sem_flg = flg;
return semop(lock->semid, opbuf, 1);
}
int sem_lock_try_acquire(sem_lock_t *lock)
{
return sem_lock_op(lock, -1, SEM_UNDO | IPC_NOWAIT);
}
int sem_lock_acquire(sem_lock_t *lock)
{
return sem_lock_op(lock, -1, SEM_UNDO);
}
int sem_lock_release(sem_lock_t *lock)
{
return sem_lock_op(lock, 1, SEM_UNDO);
}
int sem_lock_wait(sem_lock_t *lock)
{
if (lock == NULL)
return -2;
int ret = 0;
while (1)
{
ret = sem_lock_op(lock, 0, 0);
if (ret < 0)
{
if (errno == EINTR)
{
continue;
}
else
{
perror("sem_lock_op failed");
return -1;
}
}
else
{
union semun un;
un.val = 1;
semctl(lock->semid, 0, SETVAL, un);
return 0;
}
}
return 0;
}
int sem_lock_notify(sem_lock_t *lock)
{
if (lock == NULL)
return -2;
union semun un;
int ret = 0;
un.val = 0;
while (1)
{
ret = semctl(lock->semid, 0, SETVAL, un);
if (ret < 0)
{
if (errno == EINTR)
continue;
else
{
perror("semctl failed");
return -1;
}
}
else
{
return 0;
}
}
return 0;
}