本文概要:

敏捷开发大家想必知道并且评价甚高,缩短开发周期,提高开发质量。将大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. POJ 1176 Party Lamps (DFS)

    对于一束灯光.提供四种改变彩灯状态(ON<=>OFF)的操作:a.改变全部彩灯状态:b.改变奇数彩灯状态.c.改变偶数彩灯状态:d.改变3k+1号彩灯状态(1,4,7,10...). 给定 ...

  2. 深入理解学习Git工作流(转)

    个人在学习git工作流的过程中,从原有的 SVN 模式很难完全理解git的协作模式,直到有一天我看到了下面的文章,好多遗留在心中的困惑迎刃而解,于是我将这部分资料进行整理放到了github上,欢迎st ...

  3. NLP | 自然语言处理 - 解析(Parsing, and Context-Free Grammars)

    什么是解析? 在自然语言的学习过程,个人一定都学过语法,比如句子能够用主语.谓语.宾语来表示.在自然语言的处理过程中.有很多应用场景都须要考虑句子的语法,因此研究语法解析变得很重要. 语法解析有两个基 ...

  4. C#启动进程之Process

    在程序设计中,我们经常会遇到要从当前的程序跳到另一个程序的设计需求.也就是当前进程创建另一个进程.C#提供了Process使得我们很方便的实现. 1.Process基本属性和方法 Id //进程的Id ...

  5. 玩转Web之JavaScript(四)-----javaScript语法总结(四) JS中的函数

    1.function/return   function用来定义函数(位于head部分),函数包含着一些代码,这些代码只能被事件激活,或者在函数被调用时才会执行.   return 用来从函数中返回值 ...

  6. Java的socket服务UDP协议

    练习1 接收类 package com.socket.demo; import java.io.IOException; import java.net.DatagramPacket; import ...

  7. Windows创建的基本含义和进程的进程的内核

    过程 1 这意味着过程: 1.1   一个是在操作系统的内核对象管理处理. 的统计信息的地方. 1.2   还有一个是地址空间.它包括全部可运行模块或DL L 模块的代码和数据.它还包括动态内存分配的 ...

  8. vs2015基于VisualStudioOnline协同工作流程

    项目负责人登陆自己的vsonline新建项目就不多说了. 直接从邀请队友开始 项目负责人操作 被邀请的邮箱务必是可以登录visualstudio的邮箱 发送邀请后,被邀请人登陆自己的邮箱,查看邀请人发 ...

  9. Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable (转)

    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...

  10. ROADS+dijkstra的灵活运用+POJ

    ROADS Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10742   Accepted: 3949 Descriptio ...