本文概要:

敏捷开发大家想必知道并且评价甚高,缩短开发周期,提高开发质量。将大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. 系统如何端子app弄root才干

    最近由于调试USB OTG怪东西.这导致USB端口被占用,这项.虽然我是project版本号,但不能运行adb shell,这是不可能的debug该. 所以,我现在是一个系统终端apk,规划 http ...

  2. RH133读书 笔记(4) - Lab 4 System Services

    Lab 4 System Services Goal: Develop skills using system administration tools and setting up and admi ...

  3. Android应用开发:LoaderManager在Activity/Fragment中的使用分析

    LoaderManager 外部接口initLoader:起始 public <D> Loader<D> initLoader(int id, Bundle args, Loa ...

  4. 【TCP/IP 合约】 TCP/IP 基金会

    总结 : 通过学习 TCP/IP 基础, 并总结相关笔记 和 绘制思维导图 到博客上, 对 TCP/IP 框架有了大致了解, 之后開始详细学习数据链路层的各种细节协议, 并作出笔记; 博客地址 : h ...

  5. C++ Primer 学习笔记_35_STL实践与分析(9)--map种类(在)

    STL实践与分析 --map类型(上) 引: map是键-值对的集合. map类型通常能够理解为关联数组:能够通过使用键作为下标来获取一个值,正如内置数组类型一样:而关联的本质在于元素的值与某个特定的 ...

  6. MapReduce在实际编程“I/O”

    通过本篇MapReduce分析模型.深化MapReduce理解模型:和演示MapReduc进入编程模型是常用格类型和输出格公式,在这些经常使用格外公式,我们能够扩大他们的投入格公式,实例:们须要把Mo ...

  7. 更改IOS于UISearchBar撤消button底、搜索输入文本框背景中的内容和UISearchBar底

    转载请标明出处:http://blog.csdn.net/android_ls/article/details/39993433 測试的手机IOS系统版本为:6.1.3,实现过程例如以下: 1.加入U ...

  8. .Net async

    概述 先吐个槽,.NET的TPL框架,以及这篇文章想要表述的async await关键字,都是.NET语言层面本身支持的一种异步框架,代表其在编译时是可以最大化的被优化,作为内部DSL来说,.NET一 ...

  9. http报错之return error code:401 unauthorized

     http报错之return error code:401 unauthorized 依据HTTP返回码所表示的意思应该是未授权,没有输入账号和password,因此解决方法就直接在HTTP包里面 ...

  10. zoj2588 Burning Bridges --- 寻求尖端

    #include <iostream> #include <cstring> #include <string> #include <cstdio> # ...