Hi everybody,
I'm developing a daemon in c/c++ and I'm having some trouble with shared memory. I create different processes that have to access the same memory region. Everything was OK until I decided to use a vector containing objects. I read that I have to define an allocator specifing how to reserve memory. OK that what I'm trying to do. I have defined my allocator, allocate, and deallocate functions work perfectly but I have problems with the construct function, it simply raises a SIGSEGV.
Is my first time using shared memory and I'm really discouraged. Suggestions and comments are always welcome. Thanks in advance.
#ifndef _NEW_MMAPALLOCATOR_H
#define _NEW_MMAPALLOCATOR_H 1
extern "C"
{
#include <sys/types.h>
#include <sys/mman.h>
}
#include <limits>
#include <vector>
#include <iostream>
#include <iterator>
namespace leimyalloc {
template <typename T>
class mmap_allocator {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef T const * const_pointer;
typedef T& reference;
typedef T const & const_reference;
typedef T value_type;
//rebind
template <typename U>
struct rebind {
typedef mmap_allocator <U> other;
};
pointer address (reference value ) const {
return &value;
}
const_pointer address (const_reference value) const {
return &value;
}
mmap_allocator () throw () {}
mmap_allocator ( mmap_allocator const &) throw () {}
template <typename U>
mmap_allocator (mmap_allocator <U> const &) throw () {}
~mmap_allocator() throw () {}
size_type max_size () const throw() {
return ::std::numeric_limits <size_type>::max() / sizeof(T);
}
pointer allocate (size_type num, void * hint = 0) {
int fd=open("/dev/zero",O_RDWR);
if(fd==-1){
cerr << "Cannot open /dev/zero" << endl;
}
pointer p = (pointer) ::mmap(0, sizeof(pointer), PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0);
int * val = (int *)p;
if(val && *val == -1)
p = NULL;
return p;
}
void construct (pointer p, const_reference value) {
new((void *)p) T(value); //placement new
}
void destroy (pointer p) {
p->~T();
}
void deallocate (pointer p, size_type num) {
::munmap((caddr_t) p, num);
}
};
template <typename T1, typename T2>
bool operator == (mmap_allocator <T1> const &, mmap_allocator <T2> const &) throw () {
return true;
}
template <typename T1, typename T2>
bool operator != (mmap_allocator <T1> const &, mmap_allocator <T2> const &) throw () {
return false;
}
}
#end if