0% found this document useful (0 votes)
94 views

Reader Writer Using Semaphores

This document contains code for a writer program that uses semaphores to coordinate access between a writer process and reader processes. The writer process increments a count variable and uses semaphore operations to signal it can write, while reader processes print the item number being read and signal they are done reading. The processes take turns writing 10 items and reading 10 items each before exiting.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Reader Writer Using Semaphores

This document contains code for a writer program that uses semaphores to coordinate access between a writer process and reader processes. The writer process increments a count variable and uses semaphore operations to signal it can write, while reader processes print the item number being read and signal they are done reading. The processes take turns writing 10 items and reading 10 items each before exiting.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 5

AIM ::PROGRAM FOR READER WRITER USING SEMAPHORES

ROLL NO. ::s104179

CODE:
writer.c

#include<stdio.h>

#include<stdlib.h>

#include<sys/ipc.h>

#include<sys/sem.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

void main()

int i,semid,pid,key1,nsem,cnt=0,count=0;

struct sembuf sop;

semid=semget(0X20,1,IPC_CREAT|0666);

pid=fork();

while(1)

if(pid==0)
{

sleep(2);

if(cnt==10)

exit(0);

printf("\n\tReading Item----%d",cnt);

printf("\t\n");

cnt++;

sop.sem_num=0;

sop.sem_op=0;

sop.sem_flg=0;

semop(semid,&sop,1);

else

if(count==10)

exit(0);

printf("\n\tWritten Item----%d",count);

printf("\t\n");

count++;
semctl(semid,0,SETVAL,1);

sleep(1);

if(count>0)

semctl(semid,0,SETVAL,0);

OUTPUT:

sanket@linuxmint ~ $ cc writer.c

sanket@linuxmint ~ $ ./a.out

Written Item----0

Written Item----1

Reading Item----0

Written Item----2
Written Item----3

Reading Item----1

Written Item----4

Written Item----5

Reading Item----2

Written Item----6

Written Item----7

Reading Item----3

Written Item----8

Written Item----9

Reading Item----4

sanket@linuxmint ~ $

Reading Item----5
Reading Item----6

Reading Item----7

Reading Item----8

Reading Item----9

sanket@linuxmint ~ $

You might also like