本文概要:

敏捷开发大家想必知道并且评价甚高,缩短开发周期,提高开发质量。将大project独立为不同的小app开发,整个开发过程,程序可用可測,所以提高了总体的质量。基于这样的开发模式和开发理念,进程间通信必定是童鞋们必掌握技能之中的一个了,而boost库是众多库中平台支持性非常好,效果非常高之中的一个。做嵌入式或者server等应用的人肯定有所涉及。本文以手冊方式讲述boost共享内存,信号,以及消息队列的编程方式。非常easy,列出最经常使用使用方法,供大家拷贝直接使用。本文出自CSDN-固本培元。转载注明出处-leoluopy@gmail.com。

应用思路注意事项:

         信号是进程内通信,非常类似于Qt的信号槽,配合消息队列以及boost多线程使用效果非常好。

共享内存:

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string> int main(int argc, char *argv[])
{
using namespace boost::interprocess; if(argc == 1){ //Parent process
//Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
} remover; //Create a shared memory object.
shared_memory_object shm (create_only, "MySharedMemory", read_write); //Set size
shm.truncate(1000); //Map the whole shared memory in this process
mapped_region region(shm, read_write); //Write all the memory to 1
std::memset(region.get_address(), 1, region.get_size()); //Launch child process
std::string s(argv[0]); s += " child ";
if(0 != std::system(s.c_str()))
return 1;
}
else{
//Open already created shared memory object.
shared_memory_object shm (open_only, "MySharedMemory", read_only); //Map the whole shared memory in this process
mapped_region region(shm, read_only); //Check that memory was initialized to 1
char *mem = static_cast<char*>(region.get_address());
for(std::size_t i = 0; i < region.get_size(); ++i)
if(*mem++ != 1)
return 1; //Error checking memory
}
return 0;
}

信号通信:

贴出一个经常使用带參数的写法,具体的其它使用方法能够參考文章末的參考文章:

#include <boost/signal.hpp>

#include <boost/thread/thread.hpp>

#include <boost/date_time/posix_time/posix_time.hpp>

#include <iostream>

using namespace std;

using namespace boost;

float print_sum(float x, float y)

{

  std::cout << "The sum is " << x+y << std::endl;

  return x+y;

}

float print_product(float x, float y)

{

  std::cout << "The product is " << x*y << std::endl;

  return x*y;

}

float print_difference(float x, float y)

{

  std::cout << "The difference is " << x-y << std::endl;

  return x-y;

}

float print_quotient(float x, float y)

{

  std::cout << "The quotient is " << x/y << std::endl;

  return x/y;

}

int main()

{

  boost::signal<float (float , float )> sig;

  sig.connect(0, &print_sum);

  sig.connect(1, &print_product);

  sig.connect(2, &print_difference);

  sig.connect(3, &print_quotient);

  // Output 1.6667 because return by the last slot called.

  cout << sig(5, 3) << endl;   

  return 0;

}

信号槽删除及堵塞:

Seg 1: Disconnecting slots.

        boost::signals::connection c = sig.connect(HelloWorld());

        if (c.connected()) {

        // c is still connected to the signal

        sig(); // Prints "Hello, World!"

        }

        c.disconnect(); // Disconnect the HelloWorld object

        assert(!c.connected()); //c isn't connected any more

        sig(); // Does nothing: there are no connected slots

Seg 2:

        boost::signals::connection c = sig.connect(HelloWorld());

        sig(); // Prints "Hello, World!"

        c.block(); // block the slot

        assert(c.blocked());

        sig(); // No output: the slot is blocked

        c.unblock(); // unblock the slot

        sig(); // Prints "Hello, World!"

消息队列:

消息队列发送:

#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector> using namespace boost::interprocess; int main ()
{
try{
//Erase previous message queue
message_queue::remove("message_queue"); //Create a message_queue.
message_queue mq
(create_only //only create
,"message_queue" //name
,100 //max message number
,sizeof(int) //max message size
); //Send 100 numbers
for(int i = 0; i < 100; ++i){
mq.send(&i, sizeof(i), 0);
} }
catch(interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
} return 0;
}

消息队列接收:

#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector> using namespace boost::interprocess; int main ()
{
try{
//Open a message queue.
message_queue mq
(open_only //only create
,"message_queue" //name
); unsigned int priority;
message_queue::size_type recvd_size; //Receive 100 numbers
for(int i = 0; i < 100; ++i)
{
int number;
mq.receive(&number, sizeof(number), recvd_size, priority);
printf("I:%d Rec:%d\n",i,number);
if(number != i || recvd_size != sizeof(number))
return 1;
}
}
catch(interprocess_exception &ex){
message_queue::remove("message_queue");
std::cout << ex.what() << std::endl;
return 1;
}
message_queue::remove("message_queue");
return 0;
}

编译命令:

[root@localhost tmp]# g++ boost_queue_send.cpp -o queue_send -lboost_thread -lboost_system
[root@localhost tmp]# g++ boost_queue_rec.cpp -o queue_rec -lboost_thread -lboost_system

将消息队列整理了一下,能够直接方便使用例如以下:

注(BoostMsg.h)用于将函数外部化,无其它用处。

#include <BoostMsg.h>

#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <vector> using namespace boost::interprocess; int BoostMsg_CreateMsg(const char* MsgQueName,int MaxQueLen,int MaxMsgLen)
{
message_queue::remove(MsgQueName);
//Create a message_queue.
message_queue mq
(create_only //only create
,MsgQueName //name
,MaxQueLen //max message number
,MaxMsgLen //max message size
); printf("Boost Msg Created Name:%s QueLen:%d MsgMaxLen:%d \n",MsgQueName,MaxQueLen,MaxMsgLen); return 0;
} int BoostMsg_OpenMsgToSend(char* BufMsg,const char* MsgQueName,int MsgLen)
{
try{
//Erase previous message queue
//message_queue::remove("message_queue");
//Create a message_queue.
message_queue mq
(open_only //only create
,MsgQueName //name
); mq.send(BufMsg, MsgLen, 0);
}
catch(interprocess_exception &ex){
std::cout << ex.what() << std::endl;
return 1;
}
return 0;
} int BoostMsg_OpenMsgToRec(char* RecivedMsg,const char* MsgQueName,int MaxReceivedLen)
{
try{
//Open a message queue.
message_queue mq
(open_only //only create
,MsgQueName //name
); unsigned int priority;
message_queue::size_type recvd_size; memset(RecivedMsg,0,MaxReceivedLen);
mq.receive(RecivedMsg, MaxReceivedLen, recvd_size, priority);
return recvd_size; }
catch(interprocess_exception &ex){
message_queue::remove("message_queue");
std::cout << ex.what() << std::endl;
return 1;
}
message_queue::remove("message_queue");
return 0;
}

用法非常easy,就是Create 然后Send 和Rec,进程之间通信 非常方便。

參考文章:

Boost.Interprocess使用手冊翻译之四:在进程间共享内存 (Sharing
memory between processes)

http://blog.csdn.net/great3779/article/details/7226388

Windows多进程编程

http://blog.csdn.net/bxhj3014/article/details/2082255

怎样使用BOOST信号(一)

http://blog.csdn.net/liuchangyu23/article/details/4584045

Boost.Interprocess 强大的进程间通讯库

http://blog.csdn.net/linkerlin/article/details/2249906

怎样使用BOOST信号(二)

http://blog.csdn.net/liuchangyu23/article/details/4584346

boost进程间通信经常使用开发一篇全(消息队列,共享内存,信号)的更多相关文章

  1. iOS开发数据库篇—FMDB数据库队列

    iOS开发数据库篇—FMDB数据库队列 一.代码示例 1.需要先导入FMDB框架和头文件,由于该框架依赖于libsqlite库,所以还应该导入该库. 2.代码如下: // // YYViewContr ...

  2. iOS开发——优化篇—— 25个性能优化/内存优化常用方法

    1. 用ARC管理内存 ARC(Automatic ReferenceCounting, 自动引用计数)和iOS5一起发布,它避免了最常见的也就是经常是由于我们忘记释放内存所造成的内存泄露.它自动为你 ...

  3. asp.net微信开发第九篇----模板消息的使用

    微信平台的模板消息,使用起来非常好,效果如下: 和平时我们微信中关注信用卡官方微信,如果消费了,信用卡官方微信就返回一个模板消息给我们告知,余额还有多少,消费了多少. 使用的步骤,我只简单介绍了怎么使 ...

  4. python【第十一篇】消息队列RabbitMQ、缓存数据库Redis

    大纲 1.RabbitMQ 2.Redis 1.RabbitMQ消息队列 1.1 RabbitMQ简介 AMQP,即Advanced Message Queuing Protocol,高级消息队列协议 ...

  5. Android 开发笔记 “Android 的消息队列模型”

    Android是参考Windows的消息循环机制来实现Android自身的消息循环的. Android通过Looper.Handler来实现消息循环机制,Android消息循环是针对线程的(每个线程都 ...

  6. windows 驱动开发 MDL 内核层 用户层共享内存

    参考资料 https://blog.csdn.net/wdykanq/article/details/7752909 http://blog.51cto.com/laokaddk/404584 内核层 ...

  7. linux 进程间通信机制(IPC机制)一消息队列

    消息队列提供了一种从一个进程向另一个进程发送一个数据块的方法.每个数据块都被认为含有一个类型,接收进程可以独立地接收含有不同类型的数据结构.我们可以通过发送消息来避免命名管道的同步和阻塞问题.但是消息 ...

  8. 【windows 操作系统】进程间通信(IPC)简述|无名管道和命名管道 消息队列、信号量、共享存储、Socket、Streams等

    一.进程间通信简述 每个进程各自有不同的用户地址空间,任何一个进程的全局变量在另一个进程中都看不到,所以进程之间要交换数据必须通过内核,在内核中开辟一块缓冲区,进程1把数据从用户空间拷到内核缓冲区,进 ...

  9. v76.01 鸿蒙内核源码分析(共享内存) | 进程间最快通讯方式 | 百篇博客分析OpenHarmony源码

    百篇博客分析|本篇为:(共享内存篇) | 进程间最快通讯方式 进程通讯相关篇为: v26.08 鸿蒙内核源码分析(自旋锁) | 当立贞节牌坊的好同志 v27.05 鸿蒙内核源码分析(互斥锁) | 同样 ...

随机推荐

  1. 【Cocos2d-x】Mac 在 Cocos2d-x 3.X 打包Android

    今天cocos2d-x 3.0正式版最终公布了,下午特地下载了来尝尝鲜,废话不多说了. 3.0正式版的环境搭建和之前的RC版事实上是一样的,太多的教程也写了怎样搭建.今天来写写我自己是怎样来搭建的. ...

  2. Java程序猿JavaScript学习笔记(4——关闭/getter/setter)

    计划和完成这个例子中,音符的顺序如下: Java程序猿的JavaScript学习笔记(1--理念) Java程序猿的JavaScript学习笔记(2--属性复制和继承) Java程序猿的JavaScr ...

  3. wpf 9张图片的连连看

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

  4. PHP实现协同程序

    于server其中编程.为了实现异步.通常情况下,需要回调.比例如下面的代码 function send($value) { $data = process($value); onReceive($d ...

  5. MEMO:UIButton 中的图片和标题 左对齐

    UIButton setImage 和 setTitle之后.默认 image和title 对齐居中, 因为 title 长度不固定. 所以假设要几个这样有image有title的button纵向排列 ...

  6. 于windows建筑物Cocos2d-x win32开发环境

     这份文件是从cocos2d-x复制的官网.. . 在windows7上搭建COCOS2D-X开发环境并不难. 可是因为框架更新过快,非常多用户都有困难.我希望你们觉得这个教程实用. 建议:为了避 ...

  7. matlab学习------------普通dialog对话框,错误对话框errordlg,警告对话框warndlg

    Dialog对话框 语法: h = dialog('PropertyName',PropertyValue,...) 对话框的默认属性 WindowStyle的值:   {normal} | moda ...

  8. 设计模式 Template Method模式 显示程序猿的一天

    转载请注明出处:http://blog.csdn.net/lmj623565791/article/details/26276093 不断设计模式~ Template Method模式 老套路,看高清 ...

  9. [Network]Transport Layer

    1 Principles behind Transport Layer Services 1.1 Multiplexing/Demultiplexing Multiplexing at sender ...

  10. ubuntu 下安装 matplotlib

    直接使用sudo easy_install matplotlib 报错 ================================================================ ...