some-usable-scripts/c/old/semaphores_manuel_exemples/exercice_rw/sema.c

62 lines
962 B
C
Raw Normal View History

2011-03-10 14:08:58 +01:00
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
2011-03-19 12:29:52 +01:00
#include "sema.h"
2011-03-20 10:45:36 +01:00
typedef unsigned short int ushort;
2011-03-17 16:25:02 +01:00
int creat_sem(key_t cle,int val)
2011-03-10 14:08:58 +01:00
{
2011-03-17 16:25:02 +01:00
int semid;
2011-03-10 14:08:58 +01:00
2011-03-17 16:25:02 +01:00
union semun{
int val;
struct semid_ds *buf;
ushort *array;
2011-03-10 14:08:58 +01:00
} arg;
if((semid=semget(cle,1,0666+IPC_CREAT+IPC_EXCL))>= 0)
{
2011-03-17 16:25:02 +01:00
arg.val=val;
if(semctl(semid,0,SETVAL,arg)< 0)
semid = -1;
2011-03-10 14:08:58 +01:00
}
return(semid);
}
2011-03-17 16:25:02 +01:00
int del_sem(key_t cle)
{
2011-03-10 14:08:58 +01:00
return(semctl((semget(cle,0,0)),0,IPC_RMID,0));
}
2011-03-17 16:25:02 +01:00
int open_sem(key_t cle)
{
return(semget(cle,0,0));
2011-03-10 14:08:58 +01:00
}
void P(int semid)
{
2011-03-17 16:25:02 +01:00
struct sembuf psembuf;
2011-03-10 14:08:58 +01:00
2011-03-17 16:25:02 +01:00
psembuf.sem_op = -1;
psembuf.sem_flg = 0;
psembuf.sem_num = 0;
semop(semid,&psembuf,1);
2011-03-10 14:08:58 +01:00
}
void V(int semid)
{
2011-03-17 16:25:02 +01:00
struct sembuf vsembuf;
2011-03-10 14:08:58 +01:00
2011-03-17 16:25:02 +01:00
vsembuf.sem_op = 1;
vsembuf.sem_flg = 0;
vsembuf.sem_num = 0;
semop(semid,&vsembuf,1);
2011-03-10 14:08:58 +01:00
}