Please i found some examples of semaphore but i don't understand what they do?
if someone can explain to me what they do with details thank you!
Code:
pv.h
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
extern int errno;
#define SEMPERM 0600
#define TRUE 1
#define FALSE 0
#define SEMKEY 0*200
#define SEMKEYSTR "0*200"
union _semun{
int val;
struct semid_ds *stat;
unsigned short *array;
}
int p (int semid);
int v (int semid);
int initsem (key_t semkey);
void handlesem (key_t semkey);
***********************
/* initsem.c -- semaphore initialisation */
#include "pv.h"
int initsem(key_t semkey)
{
int status = 0, semid;
union semun arg;
arg.val = 1;
if((semid = semget(semkey, 1, SEMPERM|IPC_CREAT|IPC_EXCL)) == -1)
{
if (errno ==EEXIST)
semid = semget(semkey, 1, 0);
}
else /* if created ... */
{
status = semctl(semid, 0, SETVAL, arg);
}
if (semid == -1 || status == -1)
{
perror("initsem failed");
return(-1);
}
/* all okay */
else
return(semid);
}
void removesem (char *key)
{
execlp ("ipcrm", "ipcrm", "-S", key,(char *) 0);
*************************
pc.c
#include "pv.h"
int p(int semid){
struct sembuf p_buf;
p_buf.sem_num = 0;
p_buf.sem_op = -1;
p_buf.sem_flg = SEM_UNDO; /* undoes operation if process exits! */
if (semop(semid, &p_buf, 1) == -1)
{
perror("p(semid) failed");
exit(1);
}
else
return (0);
}
//p()
***************************
vc.c
#include "pv.h"
int v(int semid){
struct sembuf v_buf;
v_buf.sem_num = 0;
v_buf.sem_op = 1;
v_buf.sem_flg = SEM_UNDO;
if (semop(semid, &v_buf, 1) == -1){
perror("v(semid) failed");
exit(1);
} else
return(0);
}//v()
****************************
testsem.c
/* program for testing p() and v() -- gets mutual exclusion */
#include "pv.h"
int main(void){
key_t semkey = SEMKEY;
if(fork() == 0) handlesem(semkey);
else if(fork() == 0) handlesem(semkey);
else if(fork() == 0) handlesem(semkey);
while (wait ((int *) 0) >=0)
removesem (semkeystr);
return 0;
}//main()
void handlesem(key_t skey){
int semid, pid = getpid();
/* initialize the semaphore if we just created it */
if ((semid = initsem(skey)) < 0) exit(1);
printf("\nprocess %d BEFORE critical section\n", pid);
p(semid);
printf("\nprocess %d in critical section \n", pid);
sleep(10);
printf("\nprocess %d leaving critical section \n", pid);
v(semid); /* call semaphore SIGNAL operation */
printf("\nprocess %d is OUTSIDE critical section and quitting!\n", pid);
exit(0);
}