/* shlib.c * * "Shared Memory Library" which allocates a one dimensional array of * characters of appropriate size. * * Copyright (c) 2012 Robert Marmorstein (marmorsteinrm@longwood.edu) Released * under the terms of the GPL, version 2. See LICENSE file for details. * * For questions about the licensing of this software, contact me by mail: * Ruffner 329, Longwood University, 201 High Street, Farmville, VA 23909 */ #include #include #include #include #include #include static int shm_id; //Destroy the shared memory as soon as the last process quits (should be the server) void clean_shm() { if (shmctl(shm_id, IPC_RMID, NULL) < 0) { perror("shmctl"); exit(-1); } } //Attach to the shared memory object. If "server" is 1, creates the shared memory block and opens it for both reading and writing. //Otherwise, opens it only for reading. //Returns a character array of size width*height. char* attach_map(int server, int width, int height) { char* map; char* path; key_t key; //Get the home directory, since it's guaranteed to exist! path = getenv("HOME"); //Create an IPC key from it. key = ftok(path, 1); //Associate that key with a shared memory block if (server == 1) { shm_id = shmget(key, width*height, IPC_CREAT | S_IRUSR | S_IWUSR); atexit(clean_shm); } else { shm_id = shmget(key, width*height, S_IRUSR); } if (shm_id < 0) { perror("shmget"); exit(-1); } map = shmat(shm_id, NULL, 0); if (map == (void *)-1) { perror("shmat"); exit(-1); } return map; }