/* shm_client.c Test program for sh mem. FAC Sept 2010 * Reference: http://www.cs.cf.ac.uk/Dave/C/node27.html#SECTION002700000000000000000 * 2ndary reference: http://www.go4expert.com/forums/showthread.php?t=8461 */ /* * shm_client : client program to test shared mem. */ #include #include #include #include #include //used for sleep() in Linux. ? #include //Linux for sleep() #include //Linux req. exit() #define SHMSZ 1024 int main(int argc, char ** argv ) //argc and argv are not used here. { int shmid; key_t key; long int *shm, *s; //shared mem address int i; //loop index long int iln; key = 91810; //number just refers to creation date, is a //name for the shared mem segment. printf("shm_client: Finding shared mem...\n"); // Create (find) the segment based on key if ((shmid = shmget(key, SHMSZ, 0666)) < 0) { perror("shmget"); exit(1); } // Attach the segment to our data space. printf("shm_client: Attaching shared mem...\n"); // C++ doesnt like the c line: // if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { if ((shm = (long int *)shmat(shmid, 0, 0)) == (long int *) -1) { perror("shmat"); exit(1); } // Check to see if server has witten something // Server will set 1st loc of sh mem to 0 while(1) { //wait(); //hopefully pause for a while. wait() uses full cpu sleep(3); //sleep for 3 secs (Linux). iln = *shm; printf("shm_client: Detected %li in loc 0...\n",iln); if (iln == 0) { // yes, first location is zero, Server has witten data // Fetch the first 10 locations only. All integers. i=0; s=shm; //use "s" to increment memory index. Leave "shm" alone. while(1) { printf("shm_client: read loc. %i , ptr= %p, contains= %li\n",i,s,*s); i=i+1; s=s+1; if(i ==10) break; } printf("Enter an integer for 2nd sh mem loc.(0=quit): "); //Note: there is no check for bad input. Causes crash or endless loop. // See mstun.cpp for fix. scanf("%li", &iln); s=shm+1; *s = iln; //sets 2nd loc. to user input *shm = -1; //tells server we are done with shared mem. if(iln == 0) { printf("shm_client: exiting...\n"); exit(0); } } } //end of overall while loop. } //end of main()