/* * Project 3 - Shared memory and semaphores. * Dr. Silaghi's Operating System Concepts. * memory.c - Common shared memory functions are in here. * By Michael Rywalt - 2569 */ #include #include #include #include #include #include #include #include #include "common.h" /* Reserve enough memory for the integer used to count. */ #define SHM_SIZE (sizeof(int)) /******************** * InitSharedMemory * ******************** * * Function: InitSharedMemory * * Purpose: Initializes the shared memory segment. * * Note: It is up to the caller to (re)initialize this memory. * * Parameters: None. * * Returns: Pointer to the shared memory segment. */ void *InitSharedMemory() { int iShmid; char *pcData; key_t key; syslog(LOG_INFO, " [%s] Initializing shared memory...", __FUNCTION__); /* Get the key. */ if((key = ftok(PROJECT_KEY, PROJECT_ID)) == -1) { syslog(LOG_INFO, " [%s] Error getting key.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Create the shared memory segment. */ if((iShmid = shmget(key, SHM_SIZE, IPC_CREAT | 0644)) < 0) { syslog(LOG_INFO, " [%s] Error creating shared memory segment.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Make the data segment accessible. */ if((pcData = shmat(iShmid, NULL, 0)) == (char*) -1) { syslog(LOG_INFO, " [%s] Error activating shared memory segment.", __FUNCTION__); EXIT(EXIT_ERROR); } return pcData; } /********************** * DetachSharedMemory * ********************** * * Function: DetatchSharedMemory * * Purpose: Detatches from shared memory segment. * * Parameters: pMemory - Pointer to memory semgment. * * Returns: Nothing. */ void DetatchSharedMemory(void *pMemory) { int iShmid; key_t key; struct shmid_ds shm_ds; syslog(LOG_INFO, " [%s] Uninitializing shared memory.", __FUNCTION__); /* Get the key. */ if((key = ftok(PROJECT_KEY, PROJECT_ID)) == -1) { syslog(LOG_INFO, " [%s] Error getting key.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Get the shared memory segment. */ if((iShmid = shmget(key, SHM_SIZE, IPC_CREAT | 0644)) < 0) { syslog(LOG_INFO, " [%s] Error creating shared memory segment.", __FUNCTION__); EXIT(EXIT_ERROR); } if((shmctl(iShmid, IPC_RMID, &shm_ds)) < 0) { syslog(LOG_INFO, " [%s] Error removing shared memory.", __FUNCTION__); EXIT(EXIT_ERROR); } if(shmdt(pMemory) == -1) { syslog(LOG_INFO, " [%s] Error destroying shared memory segment.", __FUNCTION__); EXIT(EXIT_ERROR); } if(pMemory) { pMemory = NULL; } }