0% found this document useful (0 votes)
4 views2 pages

Shared Memory

This C program demonstrates the use of shared memory for inter-process communication. It creates a shared memory segment, allows the user to write a message to it, reads the message back, and then cleans up by removing the shared memory segment. Error handling is included for each operation to ensure proper execution.

Uploaded by

ggottamsindhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Shared Memory

This C program demonstrates the use of shared memory for inter-process communication. It creates a shared memory segment, allows the user to write a message to it, reads the message back, and then cleans up by removing the shared memory segment. Error handling is included for each operation to ensure proper execution.

Uploaded by

ggottamsindhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
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 1024 // Size of shared memory segment

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

// Generate a key for the shared memory segment


key = ftok(".", 'a');
if (key == -1) {
perror("ftok");
exit(1);
}

// Create a shared memory segment


shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(1);
}

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


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

// Write data to the shared memory


printf("Enter a message to write to shared memory: ");
fgets(shmaddr, SHM_SIZE, stdin);

// Detach the shared memory segment


if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(1);
}

// Read data from the shared memory


shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
exit(1);
}
printf("Data read from shared memory: %s", shmaddr);

// Detach the shared memory segment again


if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(1);
}
// Remove the shared memory segment
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(1);
}

return 0;
}

You might also like