| 1 |
// ---------------------------------------------------------------------------- |
| 2 |
// |
| 3 |
// Copyright (C) 2003-2013 Fons Adriaensen <[email protected]> |
| 4 |
// |
| 5 |
// This program is free software; you can redistribute it and/or modify |
| 6 |
// it under the terms of the GNU General Public License as published by |
| 7 |
// the Free Software Foundation; either version 3 of the License, or |
| 8 |
// (at your option) any later version. |
| 9 |
// |
| 10 |
// This program is distributed in the hope that it will be useful, |
| 11 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
// GNU General Public License for more details. |
| 14 |
// |
| 15 |
// You should have received a copy of the GNU General Public License |
| 16 |
// along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
// |
| 18 |
// ---------------------------------------------------------------------------- |
| 19 |
|
| 20 |
|
| 21 |
#include <unistd.h> |
| 22 |
#include <stdio.h> |
| 23 |
#include <fcntl.h> |
| 24 |
#include <sys/mman.h> |
| 25 |
#include "shmem.h" |
| 26 |
|
| 27 |
|
| 28 |
Shmem::Shmem (const char *name, size_t size, bool create) : |
| 29 |
_data (0), _size (0) |
| 30 |
{ |
| 31 |
int fd; |
| 32 |
|
| 33 |
if (name && *name && size) |
| 34 |
{ |
| 35 |
if (create) fd = shm_open (name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR ); |
| 36 |
else fd = shm_open (name, O_RDWR, 0); |
| 37 |
if (fd < 0) |
| 38 |
{ |
| 39 |
perror ("shm_open"); |
| 40 |
return; |
| 41 |
} |
| 42 |
if (create) ftruncate (fd, size); |
| 43 |
_size = size; |
| 44 |
_data = mmap (0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); |
| 45 |
if (_data == MAP_FAILED) |
| 46 |
{ |
| 47 |
perror ("mmap"); |
| 48 |
_data = 0; |
| 49 |
_size = 0; |
| 50 |
} |
| 51 |
close (fd); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
Shmem::~Shmem (void) |
| 57 |
{ |
| 58 |
if (_data) munmap (_data, _size); |
| 59 |
} |