#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> int main() { // Generate unique key key_t key = ftok("shmfile", 65); if (key == -1) { perror("ftok"); return 1; } // Create shared memory segment int shmid = shmget(key, 1024, 0666 | IPC_CREAT); if (shmid == -1) { perror("shmget"); return 1; } // Attach to shared memory char *str = (char*)shmat(shmid, (void*)0, 0); if (str == (char*)(-1)) { perror("shmat"); return 1; } // Write data to shared memory printf("Write Data : "); fgets(str, 1024, stdin); // Remove the newline character added by fgets str[strcspn(str, "\n")] = 0; printf("Data written in memory: %s\n", str); // Detach from shared memory if (shmdt(str) == -1) { perror("shmdt"); return 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