下面的代码创建并读取名为MyMappedFile
的文件。如果我在Linux上运行写代码(Ubuntu 14.04),我可以将此文件复制到其他Linux机器上,并且它可以正常运行。如果我将其转移到OSX并尝试在其上运行读取代码,我会收到错误:
libc++abi.dylib: terminating with uncaught exception of type boost::interprocess::lock_exception: boost::interprocess::lock_exception
相反,在OSX上写入的文件可以在OSX上读取。但是尝试在Linux下阅读它们给了我类似的信息:
terminate called after throwing an instance of 'boost::interprocess::lock_exception'
what(): boost::interprocess::lock_exception
生成的文件不同。
我用这段代码写作:
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/string.hpp>
namespace bip=boost::interprocess;
typedef bip::managed_shared_memory::segment_manager segment_manager_t;
typedef bip::basic_string<char, std::char_traits<char>, bip::allocator<char, segment_manager_t> > shared_string;
int main() {
bip::managed_mapped_file *outfile = new bip::managed_mapped_file(bip::create_only, "MyMappedFile", 1000);
outfile->find_or_construct<shared_string>("mystring")("bubza", outfile->get_segment_manager());
outfile->flush();
}
阅读:
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/string.hpp>
namespace bip=boost::interprocess;
typedef bip::managed_shared_memory::segment_manager segment_manager_t;
typedef bip::basic_string<char, std::char_traits<char>, bip::allocator<char, segment_manager_t> > shared_string;
int main() {
bip::managed_mapped_file *infile = new bip::managed_mapped_file(bip::open_only, "MyMappedFile");
shared_string *ptr = infile->find_or_construct<shared_string>("mystring")(infile->get_segment_manager());
std::cout << "I got " << *ptr << std::endl;
}
两台机器都使用GCC 4.8(Linux上为4.8.4,OSX上为4.8.5)和Boost 1.55。
为什么这些平台之间的文件兼容?
请注意,我正在谈论编写代码生成的MyMappedFile
数据文件。通过编译代码生成的可执行文件不在机器之间传输:Linux代码在Linux机器上编译,OSX代码在OSX机器上编译。