样例代码,权当做一个记录
const char* shmDir = "/dev/shm/";
std::string createFile(System &system, const std::string &fileName, const char *fileContent)
{
system.writeShm(fileName.c_str(), fileContent);
return std::string(shmDir) + fileName;
}
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <cstring>
void System::writeShm(const char *fileName, const char *fileContent)
{
int fd = shm_open(fileName, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(fd == -1)
{
throw SystemException("open shm failed.");
}
int size = std::string(fileContent).size();
if(ftruncate(fd, size) == -1)
{
close(fd);
throw SystemException("shm ftruncate failed.");
}
char *data = (char *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(data == MAP_FAILED)
{
close(fd);
throw SystemException("shm mmap failed.");
}
memcpy(data, fileContent, size);
munmap(data, size);
close(fd);
}