我编写了一个类,它打开一个共享内存通信,用于我的项目,并希望得到一个评论。
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;
};
}
#endifmylib_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);
}
```发布于 2020-02-05 11:34:49
__MYLIB_COM_HPP是一个保留标识符,您不允许在代码中使用这些标识符。<string>和<string.h>,您还可以使用std::strcpy()。另外,您不需要在标头中这样做,将其移动到实现文件中。sizeof (char)是1,因为sizeof给出的大小是char的倍数。那部分基本上是多余的。perror()错误并将其作为异常抛出也是多余的。如果捕捉到错误时不记录错误,那么您就是一个傻瓜,或者有理由忽略它,但是您不能在错误发生的地方做出这个决定。static_cast)。u_char是什么,那可能是不可移植的。mmap()返回void*,您将其转换为u_char*并存储在缓冲区中。在使用buffer的唯一情况下,首先将其转换为char*。不要,只需保留一个void*,并且只在需要时进行强制转换。char const*并将其提供给strcpy(),而不进行任何边界检查。发布于 2020-02-05 21:56:41
再加几分..。
我没有使用c++17,但是在对常量执行测试时,请考虑将常量放在左边而不是右边。这样就可以防止排字产生意想不到的后果。if (res = -1)更改res的值,而if(-1 = res)不编译。
您在类中保留了似乎不需要的变量。如果它们仅用于构造函数,则使用局部变量。也许您有其他的计划,但是res看起来特别可疑,因为如果类已经被构造,并且在您提供的代码中,它将永远不会被读取,所以它将始终是0。
https://codereview.stackexchange.com/questions/236684
复制相似问题