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

/* * shm-client version 1 - client program to demonstrate shared memory. */ #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() { int shmid; key_t key; char *shm, *s; /* * Let's use the same memory kay that the server is using. * Instead hardcoding, it could be sent automaticlaly to the * client using a pipe */ key = SHMKEY; /* * Locate the segment * or create one if no segment with key name exists. * Our intention is to locate the existing segment though. */ if ((shmid = shmget(key, SHMSZ, 0666)) < 0) { fprintf(stderr, "shmget\n"); exit(1); } /* * 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 read what the server put in the memory. */ for (s = shm; *s != '\0'; s++) putchar(*s); putchar('\n'); /* * Finally, change the first character of the * segment to '*', indicating we have read * the segment. */ *shm = '*'; /* * now detach the shared memory segment */ if ( shmdt(shm) == -1) { fprintf(stderr, "Unable to detach\n"); } exit(0); }