This repository was archived by the owner on Jun 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemlib.c
More file actions
95 lines (69 loc) · 1.62 KB
/
semlib.c
File metadata and controls
95 lines (69 loc) · 1.62 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
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include "semlib.h"
/*****************/
#if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)
/* union semun is defined by including <sys/sem.h> */
#else
/* according to X/OPEN we have to define it ourselves */
union semun {
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */
unsigned short int *array; /* array for GETALL, SETALL */
struct seminfo *__buf; /* buffer for IPC_INFO */
};
#endif
/*****************/
int sem_get(int nsem, int init_val)
{
int id;
int i;
if ( (id=semget(IPC_PRIVATE, nsem, IPC_CREAT|0777)) == -1 )
{
perror("Could not get the semafore set!");
return -1;
}
for (i=0; i<nsem; i++)
sem_setvalue(id, i, init_val);
return id;
}
void sem_close(int sem_id)
{
semctl(sem_id, 0, IPC_RMID, 0);
}
void sem_wait(int sem_id, int sem_num)
{
struct sembuf op;
op.sem_num = sem_num;
op.sem_op = -1;
op.sem_flg = 0;
if ( semop(sem_id, &op, 1) == -1 )
{
perror("Could not do the wait on the semafore");
}
}
void sem_signal(int sem_id, int sem_num)
{
struct sembuf op;
op.sem_num = sem_num;
op.sem_op = +1;
op.sem_flg = 0;
if ( semop(sem_id, &op, 1) == -1)
{
perror("Could not do the signal on the semafore");
}
}
void sem_setvalue(int sem_id, int sem_num, int value)
{
union semun val;
val.val = value;
if ( semctl(sem_id, sem_num, SETVAL, val) == -1 )
{
perror("Could not set the value on the semafore");
}
}