I wrote a class that opens a shared memory communication to use in my project, and would like a review.
mylib_com.hpp
#ifndef __MYLIB_COM_HPP
#define __MYLIB_COM_HPP
#include <sys/mman.h> /* For mmap */
#include <fcntl.h> /* For O_* in shm_open */
#include <unistd.h> /* For ftruncate and close*/
#include <string.h> /* For strcpy*/
#include <string>
namespace Myns{
class Channel{
public:
Channel(std::string name, size_t size = sizeof(char)*50);
~Channel();
void write(const char * msg);
std::string read();
private:
int memFd;
int res;
u_char * buffer;
};
}
#endif
mylib_com.cpp
#include "mylib_com.hpp"
#include <errno.h>
#include <system_error>
Myns::Channel::Channel(std::string name, size_t size){
memFd = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRWXU);
if (memFd == -1)
{
perror("Can't open file");
throw std::system_error(errno, std::generic_category(), "Couldn't open shared memory");
}
res = ftruncate(memFd, size);
if (res == -1)
{
perror("Can't truncate file");
close(memFd);
throw std::system_error(errno, std::generic_category(), "Couldn't truncate shared memory");
}
buffer = (u_char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, 0);
if (buffer == NULL)
{
perror("Can't mmap");
close(memFd);
throw std::system_error(errno, std::generic_category(), "Couldn't mmap shared memory");
}
}
Myns::Channel::~Channel(){
close(memFd);
}
void Myns::Channel::write(const char * msg){
strcpy((char*)buffer,msg);
}
```
boost::interprocess
? \$\endgroup\$ – Toby Speight Feb 5 '20 at 10:39read()
memberfunction? \$\endgroup\$ – uli Feb 5 '20 at 11:35t know I could use boost. Actually never used... For my use i just didn
t need read() right now. \$\endgroup\$ – Giuliano Feb 5 '20 at 14:17