#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;
}