72 lines
1.7 KiB
C
72 lines
1.7 KiB
C
|
#include "semp.h"
|
||
|
#include <sys/sem.h>
|
||
|
|
||
|
/**************************************************************************
|
||
|
* Authors: Gary Fleming, Amber McCloughan
|
||
|
* Class: CIS452 - Operating Systems Concepts
|
||
|
* Professor: Dr. Greg Wolffe
|
||
|
* Date: 3/14/2019
|
||
|
*
|
||
|
* Library of functions for synchronization
|
||
|
* using semaphores. Includes the classic
|
||
|
* wait() and signal() functions, as well as
|
||
|
* functions for initializing and deleting
|
||
|
* semaphores.
|
||
|
*
|
||
|
* @see semp.h for function definitions.
|
||
|
***************************************************************************/
|
||
|
|
||
|
/**
|
||
|
* Initialize a semaphore. The ID for using the other
|
||
|
* functions is returned by the function.
|
||
|
*
|
||
|
* @param value, the value to initialize the semaphore to.
|
||
|
* @return semId, the ID of the semaphore.
|
||
|
*/
|
||
|
int semp_init(int value)
|
||
|
{
|
||
|
int semId = semget(IPC_PRIVATE, 1, 00600);
|
||
|
semctl(semId, 0, SETVAL, value);
|
||
|
|
||
|
return semId;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Attempts to wait on the semaphore. Subtracts 1 from
|
||
|
* the internal value of the semaphore.
|
||
|
*
|
||
|
* @param semId, the ID of the semaphore.
|
||
|
* @return 0 if there were no errors.
|
||
|
*/
|
||
|
int semp_wait(int semId)
|
||
|
{
|
||
|
struct sembuf lock = {0, -1, SEM_UNDO};
|
||
|
semop(semId, &lock, 1);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Signals the semaphore. Adds 1 to the internal value
|
||
|
* of the semaphore.
|
||
|
*
|
||
|
* @param semId, the ID of the semaphore.
|
||
|
* @return 0 if there were no errors.
|
||
|
*/
|
||
|
int semp_signal(int semId)
|
||
|
{
|
||
|
struct sembuf unlock = {0, 1, SEM_UNDO};
|
||
|
semop(semId, &unlock, 1);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Deletes the semaphore.
|
||
|
*
|
||
|
* @param semId, the ID of the semaphore.
|
||
|
* @return 0 if there were no errors.
|
||
|
*/
|
||
|
int semp_destroy(int semId)
|
||
|
{
|
||
|
semctl(semId, 0, IPC_RMID);
|
||
|
return 0;
|
||
|
}
|