Guarder protected with semaphor #1

Merged
bartfaik04 merged 1 commits from semaphor-protection into main 2025-05-31 13:10:47 +02:00
Showing only changes of commit dc5c983dd7 - Show all commits

View File

@@ -4,20 +4,33 @@
#include <sys/types.h> #include <sys/types.h>
#include <sys/shm.h> #include <sys/shm.h>
#include <sys/ipc.h> #include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
class guarder{ class guarder{
private: private:
const int shmid; const int shmid;
const int semid;
void semaphoreOp(int op) {
struct sembuf sb{};
sb.sem_num = 0;
sb.sem_op = op;
sb.sem_flg = 0;
semop(semid, &sb, 1);
}
void setFlag(bool value) void setFlag(bool value)
{ {
semaphoreOp(-1);
bool *flag = static_cast<bool *>(shmat(shmid, nullptr, 0)); bool *flag = static_cast<bool *>(shmat(shmid, nullptr, 0));
*flag = value; *flag = value;
shmdt(flag); shmdt(flag);
semaphoreOp(1);
} }
public: public:
guarder() : shmid(shmget(IPC_PRIVATE, sizeof(bool), 0666 | IPC_CREAT)) guarder() : shmid(shmget(IPC_PRIVATE, sizeof(bool), 0666 | IPC_CREAT)), semid(semget(IPC_PRIVATE, 1, 0666 | IPC_CREAT))
{ {
setFlagOff(); setFlagOff();
} }
@@ -34,15 +47,18 @@ public:
bool isFlagOn() bool isFlagOn()
{ {
semaphoreOp(-1);
bool *flag = static_cast<bool *>(shmat(shmid, nullptr, 0)); bool *flag = static_cast<bool *>(shmat(shmid, nullptr, 0));
bool ret = *flag; bool ret = *flag;
shmdt(flag); shmdt(flag);
semaphoreOp(1);
return ret; return ret;
} }
~guarder() ~guarder()
{ {
shmctl(shmid, IPC_RMID, nullptr); shmctl(shmid, IPC_RMID, nullptr);
semctl(semid, 0, IPC_RMID);
} }
}; };