Truncate shared memory object

This commit is contained in:
Alex Kotov 2020-12-13 17:04:16 +05:00
parent 8095a02029
commit 6843ab569a
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
3 changed files with 28 additions and 0 deletions

View File

@ -36,8 +36,10 @@ AC_CHECK_HEADERS([stdlib.h])
AC_CHECK_HEADERS([string.h])
AC_CHECK_HEADERS([sys/mman.h])
AC_CHECK_HEADERS([sys/stat.h])
AC_CHECK_HEADERS([unistd.h])
AC_CHECK_FUNCS([ftruncate])
AC_CHECK_FUNCS([fstat])
AC_CHECK_FUNCS([munmap])
AC_CHECK_FUNCS([strcpy])
AC_CHECK_FUNCS([strlen])
@ -45,4 +47,6 @@ AC_CHECK_FUNCS([strlen])
AC_SEARCH_LIBS([shm_open], [rt])
AC_SEARCH_LIBS([shm_unlink], [rt])
AC_CHECK_MEMBER([struct stat.st_size], [], [], [#include <sys/stat.h>])
AC_OUTPUT

View File

@ -21,6 +21,8 @@ enum Shmemq_Error {
SHMEMQ_ERROR_MALLOC = 1,
SHMEMQ_ERROR_INVALID_NAME = 2,
SHMEMQ_ERROR_SHARED_MEMORY = 3,
SHMEMQ_ERROR_FSTAT = 4,
SHMEMQ_ERROR_FTRUNCATE = 5,
};
struct Shmemq_FrameHeader {

View File

@ -2,6 +2,8 @@
#include "config.h"
#endif
#define _POSIX_C_SOURCE 200809L
#include <shmemq.h>
#include <fcntl.h>
@ -9,6 +11,7 @@
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
struct Shmemq *shmemq_new(
const char *const name,
@ -59,6 +62,25 @@ enum Shmemq_Error shmemq_init(
if (shmemq->shm_id == -1) return SHMEMQ_ERROR_SHARED_MEMORY;
struct stat statbuf;
if (fstat(shmemq->shm_id, &statbuf) != 0) return SHMEMQ_ERROR_FSTAT;
const size_t min_size =
shmemq->is_consumer ? sizeof(struct Shmemq_BufferHeader) : size;
if ((size_t)statbuf.st_size < min_size) {
if (ftruncate(shmemq->shm_id, min_size) != 0) {
return SHMEMQ_ERROR_FTRUNCATE;
}
}
if (fstat(shmemq->shm_id, &statbuf) != 0) return SHMEMQ_ERROR_FSTAT;
if ((size_t)statbuf.st_size < size && !shmemq->is_consumer) {
if (ftruncate(shmemq->shm_id, size) != 0) return SHMEMQ_ERROR_FTRUNCATE;
}
shmemq->buffer = NULL;
return SHMEMQ_ERROR_NONE;