cbuf.c 2.09 KB
#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 <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#include "class.h"
#include "interface/class.h"

#include "cbuf.h"


static void dtor(void*);

static
void
ctor(void * _this, va_list * params)
{
	Cbuf   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) + 7 + 2);
	sprintf(this->shm_name, "/%06d_%s", getpid(), shm_name);

	/**
	 * align size at page boundary.
	 * increase as neccessary
	 */
	size        = va_arg(*params, size_t);
	size        = (0 >= size)? 1 : (0 != size%psize)? (size/psize)+1 : size/psize;
	this->bsize = psize * size;

	while (0 == state) {
		shm = shm_open(this->shm_name, O_RDWR|O_CREAT|O_EXCL, S_IRWXU);
		if (-1 == shm) {
			break;
		}

		if (-1 == ftruncate(shm, this->bsize)) {
			break;
		}

		this->data = mmap (0, this->bsize << 1,
				PROT_READ|PROT_WRITE, MAP_SHARED, shm, 0);
		if (this->data == MAP_FAILED) {
			this->data = NULL;
			break;
		}   

		munmap(this->data + this->bsize, this->bsize);

		this->mirror = mmap (this->data + this->bsize, this->bsize,
				PROT_READ|PROT_WRITE, MAP_SHARED, shm, 0);
		if (this->mirror != this->data + this->bsize) {
			if (this->mirror == this->data - this->bsize) {
				this->data    = 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)
{
	Cbuf this = _this;

	if (NULL != this->shm_name) {
		free(this->shm_name);
		this->shm_name = NULL;
	}

	if (NULL != this->data) {
		munmap(this->data, this->bsize);
		this->data = NULL;
	}

	if (NULL != this->mirror) {
		munmap(this->mirror, this->bsize);
		this->mirror = NULL;
	}
}

INIT_IFACE(Class, ctor, dtor, NULL);
CREATE_CLASS(Cbuf, NULL, IFACE(Class));

// vim: set ts=4 sw=4: