This repository has been archived on 2021-08-17. You can view files and clone it, but cannot push or open issues or pull requests.
unix/fb_arc_set/shared/shm.c

65 lines
1.6 KiB
C

#ifndef LIBRARIES
#define LIBRARIES
#define _GNU_SOURCE
#include <fcntl.h> ///< For O_* constants *
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#endif
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#define BUFFER_SHM_NAME "/11777707_buff"
int create_shmfd(char *shm_name) {
int shmfd = shm_open(shm_name, O_RDWR | O_CREAT, 0600);
if(shmfd == -1) {
fprintf(stderr, "ERROR: Failed creating shared memory object\n");
exit(EXIT_FAILURE);
}
return shmfd;
}
void truncate_shm(int shmfd, size_t shm_size) {
if(ftruncate(shmfd, shm_size) < 0) {
fprintf(stderr, "ERROR: Failed truncating shared memory object\n");
exit(EXIT_FAILURE);
}
}
void* open_shm(int shmfd, size_t shm_size) {
void* shm;
shm = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if(shm == MAP_FAILED) {
fprintf(stderr, "ERROR: Failed mapping shared memory object\n");
exit(EXIT_FAILURE);
}
return shm;
}
void write_to_shm(void* shm, char *message, size_t message_size) {
memcpy(shm, message, message_size);
}
void close_shm(void* shm, size_t shm_size) {
if (munmap(shm, shm_size) == -1) {
fprintf(stderr, "ERROR: Failed unmapping shared memory object\n");
exit(EXIT_FAILURE);
}
}
void destroy_shm(char *shm_name, int shmfd) {
if (shm_unlink(shm_name) == -1) {
fprintf(stderr, "ERROR: Failed unlinking shared memory object\n");
exit(EXIT_FAILURE);
}
if(close(shmfd) < 0) {
fprintf(stderr, "ERROR: Failed closing file descriptor\n");
exit(EXIT_FAILURE);
}
}