00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #include <memory>
00020
00021 #include <unistd.h>
00022 #include <errno.h>
00023 #include <sys/types.h>
00024 #include <sys/ipc.h>
00025 #include <sys/sem.h>
00026 #include <sys/types.h>
00027
00028
00029 #include "LOW_semaphoreSet_SysV.h"
00030
00031
00032
00033
00034
00035
00036
00037 LOW_semaphoreSet_SysV::LOW_semaphoreSet_SysV( const LOW_semaphoreSetFactory::semSetIPCKey_t inKey, const unsigned int inSemCount, const unsigned int inInitVal) :
00038 semSetKey( inKey)
00039 {
00040 if ( (semSetID=semget( semSetKey, inSemCount, SEM_PERMS)) == -1 ) {
00041
00042 if ( errno == ENOENT ) {
00043
00044 if ( (semSetID=semget( semSetKey, inSemCount, SEM_PERMS | IPC_CREAT)) == -1 )
00045 throw semSet_error( errno, "Failed to create new semaphore set", __FILE__, __LINE__);
00046
00047 unsigned short *initVal = (unsigned short *)malloc( sizeof( unsigned short) * inSemCount);
00048 for( unsigned int a=0; a<inSemCount; ++a)
00049 initVal[a] = inInitVal;
00050
00051 int retVal = semctl( semSetID, 0, SETALL, initVal);
00052
00053 free( initVal);
00054
00055 if ( retVal == -1 )
00056 throw semSet_error( errno, "Failed to set initial semaphore values", __FILE__, __LINE__);
00057
00058 }
00059 else {
00060 throw semSet_error( errno, "Error getting semaphore set", __FILE__, __LINE__);
00061 }
00062 }
00063 }
00064
00065
00066 LOW_semaphoreSet_SysV::~LOW_semaphoreSet_SysV()
00067 {
00068 semctl( semSetID, 0, IPC_RMID);
00069 }
00070
00071
00072
00073
00074
00075
00076
00077
00078 void LOW_semaphoreSet_SysV::decSem( const unsigned int inSemNo) const
00079 {
00080
00081
00082 struct sembuf semAction;
00083
00084 semAction.sem_num = inSemNo;
00085 semAction.sem_op = -1;
00086 semAction.sem_flg = SEM_UNDO;
00087
00088 if ( semop( semSetID, &semAction, 1) == -1 )
00089 throw semSet_error( errno, "semop() failed when decreasing semaphore", __FILE__, __LINE__);
00090 }
00091
00092
00093 void LOW_semaphoreSet_SysV::incSem( const unsigned int inSemNo) const
00094 {
00095
00096
00097 struct sembuf semAction;
00098
00099 semAction.sem_num = inSemNo;
00100 semAction.sem_op = 1;
00101 semAction.sem_flg = SEM_UNDO;
00102
00103 if ( semop( semSetID, &semAction, 1) == -1 )
00104 throw semSet_error( errno, "semop() failed when increasing semaphore", __FILE__, __LINE__);
00105 }