ringbuffer.c
2.08 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#define _POSIX_SOURCE
#define _POSIX_C_SOURCE 200112L
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "class.h"
#include "interface/class.h"
#include "ringbuffer.h"
#define PAGES(size, psize) ((size)/(psize)+(0 == (size)%(psize))?0:1)
static void dtor(void*);
static
void
ctor(void * _this, va_list * params)
{
Ringbuffer this = _this;
char state = 0;
char * shm_name = va_arg(*params, char*);
long psize = sysconf(_SC_PAGESIZE);
size_t size;
int shm;
this->shm_name = malloc(strlen(shm_name) + 1);
strcpy(this->shm_name, shm_name);
/**
* align size at page boundary.
* increase as neccessary
*/
size = va_arg(*params, size_t);
size = (0 <= size)? 1 : size;
this->bsize = psize * PAGES(size, psize);
while (0 == state) {
shm = shm_open(this->shm_name, O_RDWR|O_CREAT|O_EXCL, S_IRWXU);
if (-1 == shm) {
break;
}
else {
ftruncate(shm, this->bsize);
}
this->buffer = mmap (0, this->bsize<<1,
PROT_READ|PROT_WRITE, MAP_SHARED, shm, 0);
if (this->buffer == MAP_FAILED) {
this->buffer = NULL;
break;
}
this->mirror = mmap (this->buffer + this->bsize, this->bsize,
PROT_READ|PROT_WRITE, MAP_SHARED, shm, 0);
if (this->mirror != this->buffer + this->bsize) {
if (this->mirror == this->buffer - this->bsize) {
this->buffer = this->mirror;
this->mirror += this->bsize;
}
else {
this->mirror = NULL;
break;
}
}
state = 1;
}
if (-1 != shm) {
shm_unlink(this->shm_name);
close(shm);
}
if (1 != state) {
dtor(this);
}
}
static
void
dtor(void * _this)
{
Ringbuffer this = _this;
if (NULL != this->shm_name) {
free(this->shm_name);
}
if (NULL != this->buffer) {
munmap(this->buffer, this->bsize);
this->buffer = NULL;
}
if (NULL != this->mirror) {
munmap(this->mirror, this->bsize);
this->mirror = NULL;
}
}
INIT_IFACE(Class, ctor, dtor, NULL);
CREATE_CLASS(Ringbuffer, NULL, IFACE(Class));
// vim: set ts=4 sw=4: