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

LAB5 shared memory

Uploaded by

rohitm04122002
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

LAB5 shared memory

Uploaded by

rohitm04122002
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

#define SHM_SIZE 100

int main() {
key_t key;
int shmid;
char *shm_ptr;
int msg_id = 1;

// Generate a unique key


key = ftok("writer_reader_shared_memory", 'R');

// Create a shared memory segment


shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
exit(EXIT_FAILURE);
}

// Attach the shared memory segment to the writer's address space


shm_ptr = shmat(shmid, NULL, 0);
if (shm_ptr == (char *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}

// Enter a loop to send multiple messages


while (1) {
// Get input from the user for the message to be sent
printf("Enter message to send (type 'exit' to quit): ");
fgets(shm_ptr, SHM_SIZE, stdin);

// Check if the user wants to quit


if (strncmp(shm_ptr, "exit", 4) == 0)
break;

// Update the identifier for the next message


sprintf(shm_ptr, "%d: %s", msg_id++, shm_ptr);

// Detach the shared memory segment


shmdt(shm_ptr);
}

return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#define SHM_SIZE 100

int main() {
key_t key;
int shmid;
char *shm_ptr;

// Generate the same key as the writer


key = ftok("writer_reader_shared_memory", 'R');

// Get the shared memory segment


shmid = shmget(key, SHM_SIZE, 0666);
if (shmid < 0) {
perror("shmget");
exit(EXIT_FAILURE);
}

// Attach the shared memory segment to the reader's address space


shm_ptr = shmat(shmid, NULL, 0);
if (shm_ptr == (char *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}

// Enter a loop to receive and print multiple messages


while (1) {
// Read the message from the shared memory
printf("Message received: %s", shm_ptr);

// Detach the shared memory segment


shmdt(shm_ptr);
}

return 0;
}

Enter message to send (type 'exit' to quit): Hello, reader!


Enter message to send (type 'exit' to quit): How are you?
Enter message to send (type 'exit' to quit): I'm fine, thank you!
Enter message to send (type 'exit' to quit): exit

Message received: 1: Hello, reader!


Message received: 2: How are you?
Message received: 3: I'm fine, thank you!

You might also like