shm.c 1.56 KB
Newer Older
1 2
#ifndef LIBRARIES
#define LIBRARIES
3
#define _GNU_SOURCE
4
#include <fcntl.h> ///< For O_* constants *
5 6 7
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
8 9
#endif

10
#include <string.h>
11 12
#include <sys/mman.h>
#include <sys/types.h>
13

14
#define BUFFER_SHM_NAME "/11777707_buff"
15

16
int create_shmfd(char *shm_name) {
17 18
    int shmfd = shm_open(shm_name, O_RDWR | O_CREAT, 0600);
    if(shmfd == -1) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
19
        fprintf(stderr, "ERROR: Failed creating shared memory object\n");
20 21
        exit(EXIT_FAILURE);
    }
22 23
    return shmfd;
}
24

25
void* open_shm(int shmfd, size_t shm_size) {
26
    if(ftruncate(shmfd, shm_size) < 0) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
27
        fprintf(stderr, "ERROR: Failed truncating shared memory object\n");
28 29 30 31 32 33 34
        exit(EXIT_FAILURE);
    }

    void* shm;
    shm = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);

    if(shm == MAP_FAILED) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
35
        fprintf(stderr, "ERROR: Failed mapping shared memory object\n");
36 37 38 39 40 41 42 43 44 45 46 47
        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) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
48
        fprintf(stderr, "ERROR: Failed unmapping shared memory object\n");
49 50 51 52
        exit(EXIT_FAILURE);
    }
}

53
void destroy_shm(char *shm_name, int shmfd) {
54
    if (shm_unlink(shm_name) == -1) {
Ivaylo Ivanov's avatar
Ivaylo Ivanov committed
55
        fprintf(stderr, "ERROR: Failed unlinking shared memory object\n");
56 57
        exit(EXIT_FAILURE);
    }
58 59 60 61
    if(close(shmfd) < 0) {
        fprintf(stderr, "ERROR: Failed closing file descriptor\n");
        exit(EXIT_FAILURE);
    }
62
}