2019-01-12 11:39:01 +00:00
|
|
|
#ifndef LIBRARIES
|
|
|
|
#define LIBRARIES
|
2019-01-11 15:44:38 +00:00
|
|
|
#define _GNU_SOURCE
|
2019-01-12 11:39:01 +00:00
|
|
|
#include <fcntl.h> ///< For O_* constants *
|
2019-01-11 15:44:38 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <unistd.h>
|
2019-01-12 11:39:01 +00:00
|
|
|
#endif
|
|
|
|
|
2019-01-11 15:44:38 +00:00
|
|
|
#include <string.h>
|
2019-01-12 11:39:01 +00:00
|
|
|
#include <sys/mman.h>
|
|
|
|
#include <sys/types.h>
|
2019-01-11 15:44:38 +00:00
|
|
|
|
2019-01-12 11:39:01 +00:00
|
|
|
#define BUFFER_SHM_NAME "/11777707_buff"
|
2019-01-11 15:44:38 +00:00
|
|
|
|
2019-01-12 11:39:01 +00:00
|
|
|
int create_shmfd(char *shm_name) {
|
2019-01-11 15:44:38 +00:00
|
|
|
int shmfd = shm_open(shm_name, O_RDWR | O_CREAT, 0600);
|
|
|
|
if(shmfd == -1) {
|
2019-01-11 16:23:54 +00:00
|
|
|
fprintf(stderr, "ERROR: Failed creating shared memory object\n");
|
2019-01-11 15:44:38 +00:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
2019-01-12 11:39:01 +00:00
|
|
|
return shmfd;
|
|
|
|
}
|
2019-01-11 15:44:38 +00:00
|
|
|
|
2019-01-12 11:39:01 +00:00
|
|
|
void* open_shm(int shmfd, size_t shm_size) {
|
2019-01-11 15:44:38 +00:00
|
|
|
if(ftruncate(shmfd, shm_size) < 0) {
|
2019-01-11 16:23:54 +00:00
|
|
|
fprintf(stderr, "ERROR: Failed truncating shared memory object\n");
|
2019-01-11 15:44:38 +00:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
void* shm;
|
|
|
|
shm = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
|
|
|
|
|
|
|
|
if(shm == MAP_FAILED) {
|
2019-01-11 16:23:54 +00:00
|
|
|
fprintf(stderr, "ERROR: Failed mapping shared memory object\n");
|
2019-01-11 15:44:38 +00:00
|
|
|
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) {
|
2019-01-11 16:23:54 +00:00
|
|
|
fprintf(stderr, "ERROR: Failed unmapping shared memory object\n");
|
2019-01-11 15:44:38 +00:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-12 11:39:01 +00:00
|
|
|
void destroy_shm(char *shm_name, int shmfd) {
|
2019-01-11 15:44:38 +00:00
|
|
|
if (shm_unlink(shm_name) == -1) {
|
2019-01-11 16:23:54 +00:00
|
|
|
fprintf(stderr, "ERROR: Failed unlinking shared memory object\n");
|
2019-01-11 15:44:38 +00:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
2019-01-12 11:39:01 +00:00
|
|
|
if(close(shmfd) < 0) {
|
|
|
|
fprintf(stderr, "ERROR: Failed closing file descriptor\n");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
2019-01-11 15:44:38 +00:00
|
|
|
}
|