The following programs are developed to test process synchronization using semaphore. Here, we have designed two programs semaphorea.c and semaphoreb.c which are contending to run in the critical section. And the program seminit.c is initializing the semaphore. Hence you have to run seminit.c first, then you have to run the other programs, semaphorea.c and semaphoreb.c .
Source code of seminit.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#define KEY (1492)
void main()
{
int id;
union semun
{
int val;
struct semid_ds *buf;
ushort * array;
} my_sema;
my_sema.val = 0;
id = semget(KEY, 1, 0666 | IPC_CREAT);
if(id < 0)
{
fprintf(stderr, "Unable to obtain semaphore.\n");
exit(0);
}
if( semctl(id, 0, SETVAL, my_sema) < 0)
{
fprintf(stderr, "Cannot set semaphore value.\n");
}
else
{
fprintf(stderr, "Semaphore %d initialized.\n", KEY);
}
}
Source code of semaphorea.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define KEY (1492)
void main()
{
int id;
struct sembuf operations[1];
int retval;
id = semget(KEY, 1, 0666);
if(id < 0)
{
fprintf(stderr, "Program semaphorea cannot find semaphore, exiting.\n");
exit(0);
}
printf("Program semaphorea about to do a V-operation. \n");
operations[0].sem_num = 0;
operations[0].sem_op = 1;
operations[0].sem_flg = 0;
retval = semop(id, operations, 1);
if(retval == 0)
{
printf("Successful V-operation by program semaphorea.\n");
}
else
{
printf("semaphorea: V-operation did not succeed.\n");
perror("REASON");
}
}
Source code of semaphoreb.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define KEY (1492)
void main()
{
int id;
struct sembuf operations[1];
int retval;
id = semget(KEY, 1, 0666);
if(id < 0)
{
fprintf(stderr, "Program semaphoreb cannot find semaphore, exiting.\n");
exit(0);
}
printf("Program semaphoreb about to do a P-operation. \n");
printf("Process id is %d\n", getpid());
operations[0].sem_num = 0;
operations[0].sem_op = -1;
operations[0].sem_flg = 0;
retval = semop(id, operations, 1);
if(retval == 0)
{
printf("Successful P-operation by program semaphoreb.\n");
printf("Process id is %d\n", getpid());
}
else
{
printf("semaphoreb: P-operation did not succeed.\n");
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.