Mon 16 Mar 11:09:06 CET 2026

This commit is contained in:
sbosse 2026-03-16 11:11:36 +01:00
parent 729de81e84
commit a5482acbd8

76
src/shm.c Normal file
View File

@ -0,0 +1,76 @@
/*
* Shared Memory Control
*/
#include "config.h"
#if SHM>0
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h>
#include <sys/types.h>
#include "shm.h"
/*
Allocate entire SHM segment.
*buf must be either 0 or a valid vaddr
key must start with /
*/
int allocate_shm(char *key, int bufsize, void **buf) {
int oflags = O_RDWR|O_CREAT;
int fd = shm_open(key, oflags, 0644 );
ftruncate(fd, bufsize);
*buf = mmap(*buf, bufsize, PROT_READ|PROT_WRITE, MAP_SHARED|(*buf?MAP_FIXED:0), fd, 0);
shm_header_entry_t *root = (shm_header_entry_t*)buf;
root->type=SMS_ROOT;
root->addr=0;
root->size=1;
return fd;
}
int free_shm(char *key) {
return shm_unlink(key);
}
/*
Open SHm segment
*buf must be either 0 or a valid vaddr
*/
int open_shm(char *key, int *bufsize, void **buf) {
int oflags = O_RDWR;
int fd = shm_open(key, oflags, 0644 );
struct stat sb;
fstat(fd, &sb);
*bufsize = sb.st_size;
*buf = mmap(*buf, *bufsize, PROT_READ|PROT_WRITE, MAP_SHARED|(*buf?MAP_FIXED:0), fd, 0);
return fd;
}
void close_shm(int fd) {
close(fd);
}
/*
Allocate space for a structure or data segment from SHM buffer
*/
void *allocate_section(void *buf,shm_section_t type,int size) {
shm_header_entry_t *root = (shm_header_entry_t*)buf; // size is next free entry index in the header segment
shm_header_entry_t *top = (shm_header_entry_t*)&((char*)buf)[root->size*sizeof(shm_header_entry_t)];
if (root->size==1) {
top->addr=sizeof(shm_header_entry_t);
} else {
shm_header_entry_t *last = (shm_header_entry_t*)(top-sizeof(shm_header_entry_t));
top->addr=last->addr+last->size;
}
top->size=size;
root->size++;
return 0;
}
#endif /* SHM */