Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

? ? D efine constants const int B U F F E R S IZE = 1 0 0 ; const int S H A

??Define constants
const int BUFFERSIZE =100;
const int SHAREDMEMORYKEY=1234;
???
Shared memory structure
struct SharedMemory {
int buffer[BUFFERSIZE];
int in;??Index to write into the buffer
int out;??Index to read from the buffer
};
???
Function to save an integer into the circular buffer
void saveIntegerToBuffer(int value){
??Create or open the shared memory segment
int shmfd=shmopen("mysharedmemory", OCREAT |ORDWR,0666);
if(shmfd==-1){
perror("shmopen");
exit(EXITFAILURE);
}
??Set the size of the shared memory segment
ftruncate(shmfd, sizeof(SharedMemory));
??Map the shared memory segment into the address space of the process
SharedMemory *sharedmemory =(SharedMemory*) mmap(NULL, sizeof(SharedMemory),PROTREAD |PROTWRITE, MAPSHARED, shmfd,0);
if(sharedmemory ==MAPFAILED){
perror("mmap");
exit(EXITFAILURE);
}
??Close the file descriptor
close(shmfd);
??Place a mutex lock to protect critical section
??(Assumemutexlock and mutexunlock functions are provided)
mutexlock(&sharedmemorymutex);
??Check if buffer is full
while ((sharedmemoryin+1)%BUFFERSIZE ==sharedmemoryout){
??Buffer is full, wait for consumer to consume some items
??(Assumeconditionwait function is provided)
conditionwait(&sharedmemorynotfull);
}
??Save integer into the buffer
sharedmemorybuffer[sharedmemoryin]= value;
sharedmemoryin=(sharedmemoryin+1)%BUFFERSIZE;
??Signal that buffer is not empty
conditionsignal(&sharedmemorynotempty);
??Release the mutex lock
mutexunlock(&sharedmemorymutex);
??Unmap the shared memory
munmap(sharedmemory, sizeof(SharedMemory));
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning Microsoft SQL Server 2012 Programming

Authors: Paul Atkinson, Robert Vieira

1st Edition

1118102282, 9781118102282

More Books

Students also viewed these Databases questions

Question

What is management growth? What are its factors

Answered: 1 week ago