// ----------------------------------------------------------------------------
//
//  Copyright (C) 2003-2013 Fons Adriaensen <fons@linuxaudio.org>
//    
//  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 3 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, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------


#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "shmem.h"


Shmem::Shmem (const char *name, size_t size, bool create) :
    _data (0), _size (0)
{
    int fd;

    if (name && *name && size)
    {
        if (create) fd = shm_open (name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR );
        else        fd = shm_open (name, O_RDWR, 0);
        if (fd < 0)
        {
            perror ("shm_open");
   	    return;
        }
        if (create) ftruncate (fd, size);
        _size = size; 
        _data = mmap (0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (_data == MAP_FAILED)
        {
	    perror ("mmap");
            _data = 0;
	    _size = 0;
        }
        close (fd);
    }
}


Shmem::~Shmem (void)
{
    if (_data) munmap (_data, _size);
}
