Files
externals/linux/include/celoxica/sharemem.h
T
2017-10-04 14:16:02 -04:00

126 lines
3.2 KiB
C++

#pragma once
#ifdef __cplusplus
#include "strutils.h"
#include "baseError.hpp"
# include <sys/ipc.h>
# include <sys/shm.h>
# include <stdint.h>
# include <stdexcept>
# include <string>
namespace baseutils
{
class SharedMem
{
public:
///@brief Exception thrown by SharedMem when a non expected error occurs.
class Error : public BaseError
{
public:
///@brief Construct an error message.
///@param p_text[in] A descriptive text of the error.
///@param p_where[in] The location of the error.
///@param p_error[in] The code of the error.
Error(std::string const& p_what, std::string const& p_where, int p_error = 0) :
BaseError(p_what, p_where, p_error)
{
}
};
public:
SharedMem(uint32_t p_key);
SharedMem();
SharedMem(SharedMem const& p_base);
SharedMem& operator=(SharedMem const& p_base);
~SharedMem();
bool create(int p_size, int p_rights, bool p_failIfExist=true);
void close();
void reset();
void setKey(uint32_t p_key);
bool destroy();
uint32_t key() const
{
return(m_key);
}
int id() const
{
if(m_opened)
{
return(m_id);
}
throw Error("SharedMem error: Cannot return id because shared memory has not been opened", __PRETTY_FUNCTION__);
}
int id()
{
open();
return(m_id);
}
bool created() const { return(m_created); }
bool opened() const { return(m_id != -1); }
void* attach();
void detach();
bool exists()
{
open();
return(m_id != -1);
}
bool exists() const
{
if(m_opened == false)
{
throw Error("SharedMem error: not opened", __PRETTY_FUNCTION__);
}
return(m_id != -1);
}
uint32_t nbAttach() const
{
getStat();
return(static_cast<uint32_t>(m_stat.shm_nattch));
}
std::string name() const
{
return(m_keyStr);
}
uint32_t size() const
{
getStat();
return(static_cast<uint32_t>(m_stat.shm_segsz));
}
bool isOpened() const
{
return(m_opened);
}
private:
void open();
void getStat() const;
private:
void* m_ptr;
uint32_t m_key;
int m_id;
bool m_opened;
mutable bool m_statGet;
bool m_created;
std::string m_keyStr;
mutable shmid_ds m_stat;
};
}
#endif // #ifdef __cplusplus