Get Instant Help From 5000+ Experts For
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing:Proofread your work by experts and improve grade at Lowest cost

And Improve Your Grades
myassignmenthelp.com
loader
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Guaranteed Higher Grade!
Free Quote
wave

Write a C program in a file named producer.c that:
1. Creates a shared memory segment of size 32 bytes.
2. Sleeps for 10 seconds using the sleep function.
3. Destroys the shared memory segment.
4. Exits, returning an appropriate status code.


You will need to research the Linux system calls necessary to accomplish this. To get started, refer back to Lab 4 and the shmget function. At each of the steps listed above, print the status of your program to stdout (standard out) using printf. For example:

Attaches the shared memory segment (maps it to the address space of the process).
2. Initialises the segment’s contents by writing a NULL termination character to every location.
3. Reads a message of up to 20 characters from stdin (standard input) and writes it to the segment. You can either type the message in manually or use input redirection (Lab 2) to read from a file.
4. Prints the message to stdout (standard out).
5. Sleeps for 10 seconds.
6. Detaches (unmaps) and destroys the shared memory segment.


Create a second C program in a file named consumer.c that:
1. Attaches to the shared memory segment created by the producer.
2. Reads the message stored in the segment and prints it to stdout.
3. Detaches the shared memory segment.
4. Exits, returning an appropriate status code.

Creating Shared Memory Segment Using shmget() Function

To create a Shared memory segment we have to use shmget() function. The prototype of this function is:

int shmget(key_t,size,flag);

To create a segment we need to pass a key, the size of segment and a flag to specify what way the segment will be used. If flag is IPC_CREAT , it means it is for server and 0666 for client.

So in the program we use shmget(key,32,IPC_CREAT) and it returns an ID of type int integer after sucessfully creation of segment.

And to destroy the segment, we use shmctl() function. The prototype of the function is:

shmctl(shmid,IPC_RMID,NULL);

So this function takes the shared memory ID(the ID that was returned by shmget() function), and IPC_RMID flag to indicate to remove the ID and NULL.

Here is the program:

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/shm.h>

#include<unistd.h>

int main(){

key_t key = 1256482; // You can use any key value

printf("-Using key %dn",key); // Printing the used key to create shared memory segment int shmid = shmget(key,32,IPC_CREAT); // we are creating the shared memory segment using key

printf("-Shared memory segment created with ID %dn",shmid); // Printing the ID of shared memory segment

printf("-Sleeping for 10 seconds...n");

sleep(10); // Sleeping for 10 seconds

shmctl(shmid,IPC_RMID,NULL); // destroying the shared memory segment using the ID of segment

Printf ("-Shared memory segment destroyedn");return 0;

Output1) Initially the status of shared memory segments was as in this screenshot:Then at the time of execution this is the scenario:

See the ID created at the time of execution(RIGHT TERMINAL) and the last row of LEFT TERMINAL, they are same.3) Now after the termination of the program The segment is destroyed.

Task 2:

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/shm.h>

#include<unistd.h>

key_t key = 1256482; // You can use any key value

printf("-Using key %dn",key); // Printing the used key to create shared memory segment

int shmid = shmget(key,32,IPC_CREAT); // we are creating the shared memory segment using key

printf("-Shared memory segment created with ID %dn",shmid); // Printing the ID of shared memory segment

printf("-Sleeping for 10 seconds...n");

sleep(10); // Sleeping for 10 seconds

shmctl(shmid,IPC_RMID,NULL); // destroying the shared memory segment using the ID of segmentprintf("-Shared memory segment destroyedn");Output Screenshot

TASK 3

class ProducerConsumer{

public static void main(String[] args) throws Exception{

      final PC pc=new PC();

Thread t1=new Thread(new Runnable(){
     try{

            pc.produce();        }

       catch(InterruptedException e       {

               e.printStackTrace();       });

Destroying Shared Memory Segment Using shmctl() Function

Thread t2=new Thread(new Runnable() {

try{

       pc.consume();    }

catch(InterruptedException e){
        e.printStackTrace();});

t1.start();

t2.start();

t1.join();

t2.join();}

public static class PC  {

      LinkedList list=new LinkedList();

int capacity=2;

   public void produce() throw InterruptedException{ 

        int value=0;

      while(true)        {

              synchronized(this)                   {

                         while(list.size==capacity)                       {   

                             wait();

                                    System.out.println(" Producer produced" + value);

                                 list.add(value++);

                                   notify();

                                Thread.sleep(10000);          }

public void consume( ) throws InterruptedException{              

                    while(true)                           { 

                               synchronized(this)                             {     

                                     while( list.size==0)                                        { 

                                                wait();

                                            int val=list.removeFirst();

                                            System.out.println("Consumer consumed"+ val);

                                      notify();

                                   Thread.sleep(10000);Output

Producer-Consumer Design Using Bounded Buffer and Semaphore in C

Difference between Producer and consumer thread: 

     When producer produces the product with some amount value. Having in list it checks if it is full with specified value it stops producing and reach to waiting list.

Similarly when consumer consumes the product when it reaches to empty stage with some specified value.if there is no value so consumer reach to waiting stage.

CPU handles both consumer and producer process. Here synchronized key provides valid sync between consumer and producer. wait()  method makes the object in waiting until it notifies.

notify() method notifies each waiting thread into the running stage. Thread sleep() method to pause the thread for the particular time In this process,  the inter Thread communication is required.

Task 4:

public class Solution{

public static void main(String args[]) {

Instantiate (create) buffer shared by Producer & Consumer

Buffer sharedBuffer = new BoundedBuffer();

Create the producer and consumer threads

Thread producerThread = new Thread(new Producer(sharedBuffer));

Thread consumerThread = new Thread(new Consumer(sharedBuffer));

//start() method allocates memory for a new thread in the JVM,

//and calls the run() method

producerThread.start();

consumerThread.start();

public abstract void insert(Object item);

* remove an item from the Buffer.

* Note this may be either a blocking* or non-blocking operation.

public abstract Object remove();

class BoundedBuffer implements Buffer{

private static final int BUFFER_SIZE = 500; //max size of buffer array

private int count; //number of items currently in the buffer

private int in; // points to the next free position in the buffer

private int out; // points to the first filled position in the buffer

private Object[] buffer; //array of Objects

private Semaphore mutex; //provides limited access to the buffer (mutual exclusion)

private Semaphore empty; //keep track of the number of empty elements in the array private Semaphore full; //keep track of the number of filled elements in the array

public BoundedBuffer(){

// buffer is initially empty

count = 0;

in = 0;

out = 0;

buffer = new Object[BUFFER_SIZE];

mutex = new Semaphore(1); //1 for mutual exclusion

empty = new Semaphore(BUFFER_SIZE); //array begins with all empty elements

full = new Semaphore(0); //array begins with no elements

/because this makes the producer stop running when buffer is full

mutex.swait(); //mutual exclusion

// add an item to the buffer++count;

buffer[in] = item;

//modulus (%) is the remainder of a division

//for example, 0%3=0, 1%3=1, 2%3=2, 3%3=0, 4%3=1, 5%3=2

in = (in + 1) % BUFFER_SIZE;

//buffer information feedback

if (count == BUFFER_SIZE){

System.out.println("BUFFER FULL "

+ "Producer inserted "" + item

+ "" count=" + count + ", "

+ "in=" + in + ", out=" + out);else{

System.out.println("Producer inserted "" + item

+ "" count=" + count + ", "

+ "in=" + in + ", out=" + out

mutex.signal(); //mutual exclusion

full.signal(); //keep track of number of elements (value++)

//If buffer was empty, then this wakes up the Consumer

// consumer calls this methodpublic Object remove() {Object item=null;

while (count == 0){

//if nothing in the buffer, then do nothing

//the buffer array cannot be used (because empty)

full.swait(); //keep track of number of elements (value--)

mutex.swait(); //mutual exclusion

// remove an item from the buffer--count;

item = buffer[out];

out = (out + 1) % BUFFER_SIZE;

//buffer information feedback

if (count == 0){

System.out.println("BUFFER EMPTY "

+ "Consumer removed "" + item

+ "" count=" + count + ", "

+ "in=" + in + ", out=" + out);

else{

System.out.println("Consumer removed "" + item

+ "" count=" + count + ", "+ "in=" + in + ", out=" + out);

mutex.signal(); //mutual exclusion

empty.signal(); //keep track of number of empty elements (value++)

//if buffer was full, then this wakes up the Producerreturn item;

class Producer extends Thread{

private Buffer buffer;

public Producer(Buffer b) {buffer = b;

public void run(){

Date message;

while (true) {System.out.println("Producer napping");

SleepUtilities.nap()

message = new Date();

System.out.println("Producer produced "" + message + """);

buffer.insert(message);

class Consumer extends Thread{

private Buffer buffer;

public Consumer(Buffer b) {

buffer = b;

public void run(){

Date message = null;

while (true){

System.out.println("Consumer napping");

SleepUtilities.nap();

System.out.println("Consumer wants to consume");

message = (Date)buffer.remove();

System.out.println("Consumer consumed "" + message + """);

class SleepUtilities{

private static final int NAP_TIME = 5; //max nap time in seconds

/**

* Nap between zero and NAP_TIME seconds.

public static void nap() {

nap(NAP_TIME);**

* Nap between zero and duration seconds.

public static void nap(int duration) {

int sleeptime = (int) (NAP_TIME * Math.random() );

System.out.println("Nap for " + sleeptime + " seconds");

try { Thread.sleep(sleeptime*1000); }

catch (InterruptedException e) {

System.out.println("ERROR in nap(): " + e);

References

Buhr, P. A. (2016). Control Flow Paradigms. In Understanding Control Flow (pp. 637-726). Springer, Cham.

Fifield, D., Geana, A., MartinGarcia, L., Morbitzer, M., & Tygar, J. D. (2015, October). Remote operating system classification over ipv6. In Proceedings of the 8th ACM Workshop on Artificial Intelligence and Security (pp. 57-67). ACM.

Casado, M., Amidon, K. E., Balland III, P. J., Gude, N., Pettit, J., Pfaff, B. L., ... & Wendlandt, D. J. (2015). U.S. Patent No. 9,083,609. Washington, DC: U.S. Patent and Trademark Office.

Silberschatz, A., Galvin, P. B., & Gagne, G. (2014). Operating system concepts essentials. John Wiley & Sons, Inc..

Cite This Work

To export a reference to this article please select a referencing stye below:

My Assignment Help. (2021). Shared Memory Programming And Producer-Consumer Design In C Essay.. Retrieved from https://myassignmenthelp.com/free-samples/comp9812-operating-systems/prototype.html.

"Shared Memory Programming And Producer-Consumer Design In C Essay.." My Assignment Help, 2021, https://myassignmenthelp.com/free-samples/comp9812-operating-systems/prototype.html.

My Assignment Help (2021) Shared Memory Programming And Producer-Consumer Design In C Essay. [Online]. Available from: https://myassignmenthelp.com/free-samples/comp9812-operating-systems/prototype.html
[Accessed 25 April 2024].

My Assignment Help. 'Shared Memory Programming And Producer-Consumer Design In C Essay.' (My Assignment Help, 2021) <https://myassignmenthelp.com/free-samples/comp9812-operating-systems/prototype.html> accessed 25 April 2024.

My Assignment Help. Shared Memory Programming And Producer-Consumer Design In C Essay. [Internet]. My Assignment Help. 2021 [cited 25 April 2024]. Available from: https://myassignmenthelp.com/free-samples/comp9812-operating-systems/prototype.html.

Get instant help from 5000+ experts for
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing: Proofread your work by experts and improve grade at Lowest cost

loader
250 words
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Plagiarism checker
Verify originality of an essay
essay
Generate unique essays in a jiffy
Plagiarism checker
Cite sources with ease
support
Whatsapp
callback
sales
sales chat
Whatsapp
callback
sales chat
close