Proper closing and unlinking of semaphores and shared memory

This commit is contained in:
zenon 2018-06-07 17:38:20 +02:00
parent a04c1aee71
commit 51724a3637

View File

@ -11,6 +11,12 @@ static const char *pname;
struct circ_buf *shared;
static int shmfd;
static sem_t *sUsedSpace;
static sem_t *sFreeSpace;
struct sigaction sa;
static int bestSolution[MAX_ITEMS];
@ -40,19 +46,50 @@ void initCircBuf()
void wait_sem(sem_t *sem)
{
while (sem_wait(sem) == -1) { // interrupted by system call?
printf("Interupted with error!\n"); //Just to check
while (sem_wait(sem) == -1) { // interrupted by syscall?
if (errno == EINTR) {
if(quit == 1)
if (quit == 1) {
shared->quit = 1;
if (munmap(shared, sizeof(*shared)) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
close(shmfd);
if (shm_unlink(SHM_NAME) == -1) {
perror("shm_unlink");
exit(EXIT_FAILURE);
}
sem_close(sUsedSpace);
sem_close(sFreeSpace);
sem_unlink(SEM_USED_SPACE);
sem_unlink(SEM_FREE_SPACE);
exit(EXIT_SUCCESS);
}
else continue;
}
shared->quit = 1;
if (munmap(shared, sizeof(*shared)) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
close(shmfd);
if (shm_unlink(SHM_NAME) == -1) {
perror("shm_unlink");
exit(EXIT_FAILURE);
}
sem_close(sUsedSpace);
sem_close(sFreeSpace);
sem_unlink(SEM_USED_SPACE);
sem_unlink(SEM_FREE_SPACE);
exit(EXIT_FAILURE);
}
return;
}
void getSolution(sem_t sUsedSpace, sem_t sFreeSpace)
void getSolution(sem_t *sUsedSpace, sem_t *sFreeSpace)
{
int solution[MAX_ITEMS];
for (int i = 0; i < MAX_ITEMS; i++) {
@ -60,16 +97,16 @@ void getSolution(sem_t sUsedSpace, sem_t sFreeSpace)
}
if (shared->head == -1) {
wait_sem(&sUsedSpace);
wait_sem(sUsedSpace);
shared->head = (shared->head + 1) % MAX_ITEMS;
sem_post(&sFreeSpace);
sem_post(sFreeSpace);
} else {
int i = 0;
while (shared->head != -1) {
wait_sem(&sUsedSpace);
wait_sem(sUsedSpace);
solution[i] = shared->head;
shared->head = (shared->head + 1) % MAX_ITEMS;
sem_post(&sFreeSpace);
sem_post(sFreeSpace);
i++;
}
}
@ -126,7 +163,7 @@ int main(int argc, char *argv[])
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
int shmfd = shm_open(SHM_NAME, O_RDWR | O_CREAT, PERMISSION);
shmfd = shm_open(SHM_NAME, O_RDWR | O_CREAT, PERMISSION);
if (shmfd == -1) {
perror(pname);
exit(EXIT_FAILURE);
@ -142,13 +179,14 @@ int main(int argc, char *argv[])
exit(EXIT_FAILURE);
}
sem_t *sFreeSpace = sem_open(SEM_FREE_SPACE, O_CREAT | O_EXCL, PERMISSION, MAX_ITEMS);
sem_t *sUsedSpace = sem_open(SEM_USED_SPACE, O_CREAT | O_EXCL, PERMISSION, 0);
sFreeSpace = sem_open(SEM_FREE_SPACE, O_CREAT | O_EXCL, PERMISSION, MAX_ITEMS);
sUsedSpace = sem_open(SEM_USED_SPACE, O_CREAT | O_EXCL, PERMISSION, 0);
initCircBuf();
while (quit == 0) {
getSolution(*sUsedSpace, *sFreeSpace);
wait_sem(sUsedSpace);
getSolution(sUsedSpace, sFreeSpace);
}