-
Notifications
You must be signed in to change notification settings - Fork 2
/
shmem.c
93 lines (81 loc) · 2.71 KB
/
shmem.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* @file shmem.c
* @author Dan Albert
* @date Created 11/23/2011
* @date Last updated 12/04/2011
* @version 1.0
*
* @section LICENSE
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* @section DESCRIPTION
*
* Implements functions for use with the shared memory method.
*
*/
#include <sys/mman.h>
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include "shmem.h"
bool shmem_load(struct shmem_res *res) {
int shmem_fd;
int bitmap_size;
int perfnums_size;
int processes_size;
int total_size;
int limit;
void *addr;
assert(res != NULL);
// Open the shared memory object
shmem_fd = shm_open(SHMEM_PATH, O_RDWR, S_IRUSR | S_IWUSR);
if (shmem_fd == -1) {
perror("failed to open shared memory object");
return false;
}
if (read(shmem_fd, &limit, sizeof(int)) == -1) {
perror("Could not read limit");
return false;
}
bitmap_size = limit / 8 + 1;
perfnums_size = NPERFNUMS * sizeof(int);
processes_size = NPROCS * sizeof(struct process);
total_size = sizeof(pid_t) + sizeof(int) + (2 * sizeof(sem_t)) + bitmap_size +
perfnums_size + processes_size;
// Check that the size of the shared memory object is the correct size
if (total_size != lseek(shmem_fd, 0, SEEK_END)) {
fprintf(stderr, "Shared memory object is invalid\n");
return false;
}
lseek(shmem_fd, 0, SEEK_SET); // Seek start
addr = mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmem_fd, 0);
if (addr == MAP_FAILED) {
perror("failed to map shared memory object");
return false;
}
res->addr = addr;
res->limit = res->addr;
res->manage = res->limit + 1;
res->bitmap_sem = (sem_t *)(res->manage + 1);
// limit is a single integer, so bitmap is one int past
res->bitmap = (uint8_t *)(res->bitmap_sem + 1);
res->perfect_numbers_sem = (sem_t *)(res->bitmap + bitmap_size);
res->perfect_numbers = (int *)(res->perfect_numbers_sem + 1);
res->processes = (struct process *)(res->perfect_numbers + NPERFNUMS);
res->end = res->processes + NPROCS;
return true;
}