-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore.c
77 lines (56 loc) · 1.49 KB
/
semaphore.c
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
#include "semaphore.h"
#include <errno.h>
#include <unistd.h>
#include <time.h>
#define TEST_ERROR if (errno) {fprintf(stderr, \
"%s:%d: PID=%5d: Error %d (%s)\n", \
__FILE__, \
__LINE__, \
getpid(), \
errno, \
strerror(errno));}
/* Set a semaphore to a user defined value */
int sem_set_val(int sem_id, int sem_num, int sem_val) {
return semctl(sem_id, sem_num, SETVAL, sem_val);
}
/* Try to access the resource by 1 */
int sem_reserve_1(int sem_id, int sem_num) {
struct sembuf sops;
sops.sem_num = sem_num;
sops.sem_op = -1;
sops.sem_flg = 0;
return semop(sem_id, &sops, 1);
}
int sem_reserve_1_no_wait(int sem_id, int sem_num) {
struct sembuf sops;
sops.sem_num = sem_num;
sops.sem_op = -1;
sops.sem_flg = IPC_NOWAIT;
return semop(sem_id, &sops, 1);
}
int sem_reserve_1_time(int sem_id, int sem_num){
struct sembuf sops;
struct timespec timeout;
sops.sem_num = sem_num;
sops.sem_op = -1;
sops.sem_flg = 0;
timeout.tv_sec = 0;
timeout.tv_nsec = 100000000;
return semtimedop(sem_id, &sops, 1, &timeout);
}
int sem_reserve_0(int sem_id, int sem_num) {
struct sembuf sops;
sops.sem_num = sem_num;
sops.sem_op = 0;
sops.sem_flg = 0;
return semop(sem_id, &sops, 1);
}
/* Release the resource */
int sem_release(int sem_id, int sem_num) {
struct sembuf sops;
sops.sem_num = sem_num;
sops.sem_op = 1;
sops.sem_flg = 0;
return semop(sem_id, &sops, 1);
}
/* Print all semaphore values to a string */