Shared memory reader
Thu Jun 06 2024 01:02:24 GMT+0000 (Coordinated Universal Time)
Saved by
@login
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
key_t key;
int shmid;
char *str;
// Generate unique key
key = ftok("shmfile", 65);
if (key == -1) {
perror("ftok");
exit(EXIT_FAILURE);
}
// Locate the shared memory segment
shmid = shmget(key, 1024, 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
// Attach shared memory segment
str = (char*) shmat(shmid, NULL, 0);
if (str == (char*) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
// Read from shared memory
printf("Data read from memory: %s\n", str);
// Detach shared memory segment
if (shmdt(str) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
// Remove the shared memory segment
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(EXIT_FAILURE);
}
return 0;
}
content_copyCOPY
Comments