//* Shared memory demo - server - by D. Marshall *

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define SHMKEY 5678 #define SHMSZ 4096 int main() { char c; int shmid; key_t key; char *shm, *s; /* * We'll name our shared memory segment "5678". * We'll hope that any other unrelated program would not use the same name * Use value IPC_PRIVATE to get a unique key that nobody else uses */ key = SHMKEY; /* * Create the segment if no segment with key name exists, * or get the segment id if segment with key name already exists */ if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { fprintf(stderr, "shmget\n"); exit(1); } fprintf(stdout, "The shared memory identifier is %d\n", shmid); /* * Now we attach the segment to our data space. */ if ((shm = (char *) shmat(shmid, NULL, 0)) == (char *) -1) { fprintf(stderr, "shmat\n"); exit(1); } /* * Now put some things into the memory for the * other process to read. */ s = shm; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = '\0'; /* * Finally, we wait until the other process * changes the first character of our memory * to '*', indicating that it has read what * we put there. */ while (*shm != '*') sleep(1); /* * now detach the shared memory segment */ if ( shmdt(shm) == -1) { fprintf(stderr, "Unable to detach\n"); } /* * now remove the shared memory segment */ shmctl(shmid, IPC_RMID, NULL); exit(0); }