#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define SHM_SIZE 1024 // Size of shared memory segment int main() { int shmid; key_t key; char *shm, *s; // Generate the same unique key used by the other program key = ftok(".", 'a'); // Locate the shared memory segment shmid = shmget(key, SHM_SIZE, 0666); if (shmid == -1) { perror("shmget"); exit(1); } // Attach the shared memory segment shm = shmat(shmid, NULL, 0); if (shm == (char *) -1) { perror("shmat"); exit(1); } // Read from the shared memory segment for (s = shm; *s != '\0'; s++) { putchar(*s); } putchar('\n'); // Signal to the other process that we've finished reading *shm = '*'; // Detach the shared memory segment if (shmdt(shm) == -1) { perror("shmdt"); exit(1); } 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