#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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter