/* * Project 3 - Shared memory and semaphores. * Dr. Silaghi's Operating System Concepts. * semaphore.c - Common semaphore functions. * By: Michael Rywalt - 2569 */ #include #include #include #include #include #include #include #include "common.h" /* Necessary definitions. */ #define NSEMS 1 /* Variables for external use. */ int iSemaphoreId; struct sembuf WaitMutex = {SEMMUTEX, -1, 0}; struct sembuf SignalMutex = {SEMMUTEX, 1, 0}; union semun { int iVal; struct semid_ds *buf; unsigned short *uwArray; }; /***************** * InitSemaphore * ***************** * * Function: InitSemaphore * * Purpose: Initialize the use of semaphores. * * Parameters: None. * * Returns: Semaphore ID. */ void InitSemaphore() { key_t key; union semun uArg; syslog(LOG_INFO, " [%s] Initializing semaphores.", __FUNCTION__); if((key = ftok(PROJECT_KEY, PROJECT_ID)) == -1) { syslog(LOG_INFO, " [%s] Error getting key.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Create the semaphore set. */ if((iSemaphoreId = semget(key, NSEMS, 0644 | IPC_CREAT)) == -1) { syslog(LOG_INFO, " [%s] Error getting semaphore.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Initialize the MUTEX semaphore. */ uArg.iVal = 1; if(semctl(iSemaphoreId, SEMMUTEX, SETVAL, uArg) == -1) { syslog(LOG_INFO, " [%s] Error setting MUTEX semaphore.", __FUNCTION__); EXIT(EXIT_ERROR); } } /******************** * DestroySemaphore * ******************** * * Function: DestroySemaphore * * Purpose: To uninitialize the use of semaphores. * * Parameters: None. * * Returns: Nothing. */ void DestroySemaphore() { key_t key; union semun uArg; syslog(LOG_INFO, " [%s] Uninitializing semaphores.", __FUNCTION__); if((key = ftok(PROJECT_KEY, PROJECT_ID)) == -1) { syslog(LOG_INFO, " [%s] Error getting Key.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Get the semaphore. */ if((iSemaphoreId = semget(key, 1, 0)) == -1) { syslog(LOG_INFO, " [%s] Semget: Semaphore doesn't or no longer exists.", __FUNCTION__); EXIT(EXIT_ERROR); } /* Remove the MUTEX semaphore. */ if(semctl(iSemaphoreId, SEMMUTEX, IPC_RMID, uArg) == -1) { syslog(LOG_INFO, " [%s] Error removing MUTEX semaphore.", __FUNCTION__); EXIT(EXIT_ERROR); } }