Semaphore
Semaphore is used to implement
process synchronization. This is to protect critical regions shared among
multiple processes.
Include
the following header files for shared memory
<sys/ipc.h>,
<sys/sem.h>, <sys/types.h>
System V Semaphore
System Calls
To
create a semaphore array,
int semget(key_t key, int nsems, int
semflg)
key
-> semaphore id
nsems
-> no. of semaphores in the semaphore array
semflg
-> IPC_CREATE|0664 : to create a new semaphore
IPC_EXCL|IPC_CREAT|0664 : to create new semaphore and the call
fails if the semaphore already exists
To perform operations on the
semaphore sets viz., allocating resources, waiting for the resources or freeing
the resources,
int semop(int
semid, struct
sembuf *semops, size_t
nsemops)
semidsa->
semaphore id returned by semget()
nsemops
-> the number of operations in that array
semops
-> The pointer to an array of operations to be performed on the semaphore
set.
The
structure is as follows
struct sembuf {
unsigned short sem_num; /* Semaphore set num */
short sem_op; /* Semaphore operation */
short sem_flg; /*Operation flags, IPC_NOWAIT, SEM_UNDO */
};
Element,
sem_op, in the above structure, indicates the operation that needs to be
performed −
●
If sem_op is –ve, allocate or obtain resources. Blocks the calling
process until enough resources have been freed by other processes, so that this
process can allocate.
●
If sem_op is zero, the calling process waits or sleeps until
semaphore value reaches 0.
●
If sem_op is +ve, release resources.
To
perform control operation on semaphore,
int semctl(int semid, int
semnum, int
cmd,…);
semid
-> identifier of the semaphore returned by semget() semnum -> semaphore
number
cmd -> the command to
perform on the semaphore. Ex. GETVAL, SETVAL semun -> value depends on the
cmd. For few cases, this is not applicable.
Q1. Execute and write the output of the following program for mutual exclusion.
#include<sys/ipc.h> #include<sys/sem.h>
int main()
{
int pid,semid,val; struct sembuf sop;
semid=semget((key_t)6,1,IPC_CREAT|0666); pid=fork();
sop.sem_num=0;
sop.sem_op=0; sop.sem_flg=0;
if (pid!=0)
{
sleep(1);
printf("The Parent waits for WAIT
signal\n"); semop(semid,&sop,1);
printf("The Parent WAKED UP & doing her
job\n"); sleep(10);
printf("Parent
Over\n");
}
else
{
printf("The Child sets WAIT signal & doing
her job\n"); semctl(semid,0,SETVAL,1);
sleep(10);
printf("The Child sets WAKE signal
&finished her job\n"); semctl(semid,0,SETVAL,0);
printf("Child
Over\n");
}
return 0;
}
Output :