Skip to content

Instantly share code, notes, and snippets.

@wyyqyl
Created December 24, 2013 07:28
Show Gist options
  • Save wyyqyl/8109940 to your computer and use it in GitHub Desktop.
Save wyyqyl/8109940 to your computer and use it in GitHub Desktop.
interprocess communication with boost::interprocess
#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
using namespace boost::interprocess;
const char kSharedMemory[] =
"asdv2_adblock_shared_object_{5095C5F0-D82D-4442-9A62-8769871F42D1}";
const char kMessageQueue[] =
"asdv2_adblock_shared_queue_{5095C5F0-D82D-4442-9A62-8769871F42D1}";
typedef struct _AdblockControl {
bool block_ads;
bool block_malware;
bool dont_track_me;
} AdblockControl;
class SharedMemory {
public:
SharedMemory();
~SharedMemory();
private:
managed_shared_memory* segment_;
AdblockControl* ctrl_;
};
SharedMemory::SharedMemory() : ctrl_(nullptr) {
shared_memory_object::remove(kSharedMemory);
segment_ = new managed_shared_memory(create_only, kSharedMemory, 1024);
ctrl_ = segment_->construct<AdblockControl>("AdblockControl")();
ctrl_->block_ads = ctrl_->block_malware = ctrl_->dont_track_me = true;
}
SharedMemory::~SharedMemory() { shared_memory_object::remove(kSharedMemory); }
class MessageQueue {
public:
MessageQueue();
~MessageQueue();
void Start();
private:
message_queue* queue_;
};
MessageQueue::MessageQueue() : queue_(nullptr) {
message_queue::remove(kMessageQueue);
queue_ = new message_queue(create_only, kMessageQueue, 100, 255);
}
MessageQueue::~MessageQueue() { message_queue::remove(kMessageQueue); }
void MessageQueue::Start() {
char msg[256] = {0};
unsigned int priority;
message_queue::size_type recvd_size;
while (true) {
queue_->receive(msg, sizeof(msg), recvd_size, priority);
std::string str(msg, recvd_size);
std::cout << str << std::endl;
}
}
int main() {
SharedMemory sm;
MessageQueue queue;
queue.Start();
return 0;
}
@chuongvhn
Copy link

Could you please tell me what is the relationship for the MessageQueue and SharedMemory created in the code ? I'm not clear about the creations of those, are they allocated in same memory section ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment