Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c++ boost::interprocess simple application

I want to write a simple application with boost that passes string object to other process. It compiles well, but when i try to print out string from second process, following messages are put to console and second process crashes:

../boost_1_44_0/boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp:107: void boost::interprocess::interprocess_recursive_mutex::unlock(): Assertion `res == 0' failed.

first process code:

shared_memory_object::remove(SHARED_MEMORY_NAME);
managed_shared_memory mshm(create_only, SHARED_MEMORY_NAME,  SHARED_MEMORY_SIZE ); 
mshm.construct<string>( IP_STRING_NAME )("Message to other process");
string syscall(argv[0]);
std::system( (syscall+" &").c_str()  ); //starting second process

second process code:

managed_shared_memory mshm( open_or_create, SHARED_MEMORY_NAME, SHARED_MEMORY_SIZE  );
std::pair<string * , size_t > p= mshm.find<string>(IP_STRING_NAME);
cout<<"string is "<<*p.first<<endl;

How can i make my application work in proper way ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Its not clear from your code whether you meant boost::interprocess::string or std::string, but from my few hours boost::interprocess (rather frustrating...) experience, you want neither...

So, here's a

Quick guide for strings in boost::interprocess

First, you need to define a special string:

typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> CharAllocator; 
typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> my_string;

Second, sending app should use:

// (mshm is the managed_shared_memory instance from the question)
mshm.construct<my_string>( SOME_STRINGY_NAME )(
            "Message to other process",
            mshm.get_segment_manager());

Last, reading app should:

std::pair<my_string * , size_t > p= mshm.find<my_string>(SOME_STRINGY_NAME);
cout<< "got " << p.second << " strings " << endl;
cout<< "first string is->"<<p.first->c_str()<<endl;

Note: Reason for all this complexity is this.

Cheers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...