Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Relying on the provided files, write a chat program, based on two C programs using shared memory (not pipes, nor fifo). You can safely assume

Relying on the provided files, write a chat program, based on two C programs using shared memory (not pipes, nor fifo). You can safely assume that the messages won't be long, between 1024 and 4096 bytes is more than enough. You can also assume that only one person will chat at the same time, meaning that only one of the two users can send text at the same time, this does not mean that that one user is limited to one message. This means that, user1 writes and he could write again multiple times, after user2 can reply with one or more messages.

consumer.c

#include
#include
#include
int main() {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void *ptr;
/* open the shared memory object */
shm_fd = shm_open(name, O_RDONLY, 0666);
/* memory map the shared memory object */
ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
/* read from the shared memory object */
printf("%s - ", (char *) ptr);
printf("%s - ", (char *) ptr);
printf("%s - ", (char *) ptr);
/* remove the shared memory object */
shm_unlink(name);
return 0;
}

producer.c

#include
#include
#include
#include
#include
int main() {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* strings written to shared memory */
const char *message_0 = "Hello";
const char *message_1 = "World!";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void *ptr;
/* create the shared memory object */
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory object */
ftruncate(shm_fd, SIZE);
/* memory map the shared memory object */
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
/* write to the shared memory object */
sprintf(ptr, "%s ", message_0);
ptr += strlen(message_0);
sprintf(ptr, "%s ", message_1);
ptr += strlen(message_1);
return 0;
}

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

Step: 3

blur-text-image

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

Database Concepts

Authors: David M. Kroenke, David J. Auer

7th edition

133544621, 133544626, 0-13-354462-1, 978-0133544626

More Books

Students also viewed these Databases questions

Question

How do rituals and routines express organizational values?

Answered: 1 week ago