-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore.c
98 lines (76 loc) · 1.99 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
Author : Benoit PAPILLAULT <[email protected]>
Creation : 17/12/2002
License : GPL
$Id: semaphore.c,v 1.8 2005/10/25 12:20:05 kolja_gava Exp $
*/
#include "semaphore.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
#include <errno.h>
/* for ident(1) command */
static const char id[] = "@(#) $Id: semaphore.c,v 1.8 2005/10/25 12:20:05 kolja_gava Exp $";
/*
09/12/2003 Benoit PAPILLAULT
We define union semun here (in .c file) since it's not needed in .h
file. Currently <sys/sem.h> includes <bits/sem.h> where union semun
is not defined, but _SEM_SEMUN_UNDEFINED is set to 1.
*/
#if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)
/* l'union semun est d�finie en incluant <sys/sem.h> */
#else
/* d'apr�s X/OPEN nous devons la d�finir nous-m�me */
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 semaphore_init(int count)
{
int sem;
union semun un;
sem = semget(IPC_PRIVATE, 1, 0666);
if (sem == -1)
return -1;
un.val = count;
if (semctl(sem, 0, SETVAL, un) == -1)
return(-1);
return(sem);
}
int semaphore_incr(int sem, int val)
{
int ret;
struct sembuf buf;
buf.sem_num = 0;
buf.sem_op = val;
buf.sem_flg = 0;
do{
ret = semop(sem, &buf, 1);
}while (ret<0 && errno==EINTR);
return(ret);
}
int semaphore_decr(int sem, int val)
{
int ret;
struct sembuf buf;
buf.sem_num = 0;
buf.sem_op = -val;
buf.sem_flg = 0;
do{
ret = semop(sem, &buf, 1);
}while (ret<0 && errno==EINTR);
return(ret);
}
int semaphore_done(int sem)
{
union semun un;
/* union semun is ignored when used with IPC_RMID */
if (semctl(sem, 0, IPC_RMID, un) == -1)
return(-1);
return(0);
}