我正在创建一个由两个进程使用的消息队列。其中一个正在放入某些东西,另一个正在阅读它。 消息队列遵循我创建的结构。
struct MSGQueue {
Action actions_[256];
int count;
MSGQueue() { count = 0; }
interprocess_mutex mutex;
Action Pop() {
--count;
return actions_[count];
}
void Put(Action act) {
actions_[count] = act;
++count;
}
};
Action是我创建的一个自定义类。
class Action {
public:
// Getter functions for the member
private:
std::string name_;
ActionFn action_fn_; // this is an enum
void* additional_data_;
}
我正在主程序中创建这样的共享内存
shm_messages = shared_memory_object(create_only,"MySharedMemory", read_write);
shm_messages.truncate(sizeof(MSGQueue));
region = mapped_region(shm_messages_, read_write);
在我的其他程序中,我将其打开并将一个动作放入动作的队列数组中。
boost::interprocess::shared_memory_object shm_messages_;
boost::interprocess::mapped_region region_;
shm_messages_ = shared_memory_object(open_only, "MySharedMemory", read_write);
shm_messages_.truncate(sizeof(MSGQueue));
region_ = mapped_region(shm_messages_, read_write);
//Get the address of the mapped region
void * addr = region_.get_address();
//Construct the shared structure in memory
MSGQueue * data = static_cast<MSGQueue*>(addr);
Action open_roof("OpenRoof", ActionFn::AFN_ON, NULL);
{ // Code block for scoped_lock. Mutex will automatically unlock after block.
// even if an exception occurs
scoped_lock<interprocess_mutex> lock(data->mutex);
// Put the action in the shared memory object
data->Put(open_roof);
}
主程序正在检查是否收到一些新消息,如果有新消息,则将其阅读并放入列表中。
std::vector<ghpi::Action> actions;
//Get the address of the mapped region
void * addr = region_.get_address();
//Construct the shared structure in memory
MSGQueue * data = static_cast<ghpi::Operator::MSGQueue*>(addr);
if (!data) {
std::cout << " Error while reading shared memory" << std::endl;
return actions;
}
{
scoped_lock<interprocess_mutex> lock(data->mutex);
while (data->count > 0) {
actions.push_back(data->Pop()); // memory access violation here
std::cout << " Read action from shm" << std::endl;
}
}
第二个执行动作的程序运行正常。但是运行主程序后,发现计数增加了,并试图读取并向我抛出内存访问冲突。
我不知道为什么会收到此违规错误。共享类对象或结构有什么特别的地方吗?
答案 0 :(得分:3)
让我们看一下您要在进程之间传递的对象:
class Action {
// ...
std::string name_;
}
好吧,在这里。我们有什么在这里?我们这里有一个std::string
。
您是否知道sizeof(x)
(其中x
是std::string
)将始终为您提供相同的答案,无论字符串为空还是其全部内容为“战争与和平” “?那是因为您的std::string
做了很多您不必真正考虑的工作。它负责为字符串分配需求内存,并在不再使用它时进行分配。当std::string
被复制或移动时,该类负责正确处理这些详细信息。它执行自己的内存分配和释放。您可以想到std::string
包含以下内容:
namespace std {
class string {
char *data;
size_t length;
// More stuff
};
}
通常,在典型的花园品种std::string
中,通常还有更多的功能,但这可以让您基本了解正在发生的事情。
现在尝试考虑将std::string
放入共享内存时会发生什么。您认为char
指针仍指向哪里?当然,它仍然指向进程的内存中的某个地方,std::string
会为它代表的任何字符串分配内存。您不知道在哪里,因为所有这些信息都隐藏在字符串中。
因此,您将此std::string
放置在共享内存区域中。您确实放置了std::string
本身,但是当然没有放置它包含的实际字符串。您不可能做到这一点,因为您无法访问std::string
的内部指针和数据。因此,您已经完成了此操作,现在尝试从其他过程访问此std::string
。
这不会很好地结束。
您唯一可行的选择是将std::string
替换为普通的char
数组,然后进行额外的工作以确保其正确初始化,不会溢出等。
通常,在IPC,共享内存等环境中,使用任何类型的非平凡类都不是初学者。