00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00036 #include "blocxx/BLOCXX_config.h"
00037
00038 #ifdef BLOCXX_GNU_LINUX
00039 #include "blocxx/IPCMutex.hpp"
00040 #include "blocxx/ExceptionIds.hpp"
00041
00042
00043 namespace BLOCXX_NAMESPACE
00044 {
00045
00046 const int ADD_KEY = 1;
00047 const int BLOCK_FOR_KEY = -1;
00048
00049 BLOCXX_DEFINE_EXCEPTION_WITH_ID(IPCMutex);
00050
00051
00053 IPCMutex::IPCMutex(int semKey)
00054 {
00055 m_sbuf.sem_num = 0;
00056 m_sbuf.sem_flg = 0;
00057 m_semid = semget((key_t)semKey, 1, 0666);
00058 if (m_semid == -1)
00059 {
00060 m_semid = semget((key_t)semKey, 1, IPC_CREAT | 0666);
00061 if (m_semid == -1)
00062 {
00063 BLOCXX_THROW(IPCMutexException,
00064 "Unable to create semaphore");
00065 return;
00066 }
00067 m_arg.val = 1;
00068 if (semctl(m_semid, 0, SETVAL, m_arg) != 0)
00069 {
00070 BLOCXX_THROW_ERRNO_MSG(IPCMutexException,
00071 "semctl() failed");
00072 }
00073 }
00074 }
00075
00077 void
00078 IPCMutex::wait()
00079 {
00080 m_sbuf.sem_op = BLOCK_FOR_KEY;
00081 if (semop(m_semid, &m_sbuf, 1) != 0)
00082 {
00083 BLOCXX_THROW_ERRNO_MSG(IPCMutexException,
00084 "Failed to wait on semaphore");
00085 }
00086 }
00087
00089 void
00090 IPCMutex::signal()
00091 {
00092 m_sbuf.sem_op = ADD_KEY;
00093 if (semop(m_semid, &m_sbuf, 1) != 0)
00094 {
00095 BLOCXX_THROW_ERRNO_MSG(IPCMutexException,
00096 "Failed to signal semaphore");
00097 }
00098 }
00099
00101
00102 void
00103 IPCMutex::free(int semKey)
00104 {
00105 int semid = semget((key_t)semKey, 1, 0666);
00106 if (semid != -1)
00107 {
00108 semctl(semid, 1, IPC_RMID, 0);
00109 }
00110 }
00111
00113 IPCMutexLock::IPCMutexLock(IPCMutex& sem)
00114 : m_sem(sem)
00115 {
00116 m_sem.wait();
00117 }
00118
00120 IPCMutexLock::~IPCMutexLock()
00121 {
00122 m_sem.signal();
00123 }
00124
00125 }
00126
00127 #endif // BLOCXX_GNU_LINUX