boost进程间通信经常使用开发一篇全(消息队列,共享内存,信号)
本文概要:
敏捷开发大家想必知道并且评价甚高,缩短开发周期,提高开发质量。将大project独立为不同的小app开发,整个开发过程,程序可用可測,所以提高了总体的质量。基于这样的开发模式和开发理念,进程间通信必定是童鞋们必掌握技能之中的一个了,而boost库是众多库中平台支持性非常好,效果非常高之中的一个。做嵌入式或者server等应用的人肯定有所涉及。本文以手冊方式讲述boost共享内存,信号,以及消息队列的编程方式。非常easy,列出最经常使用使用方法,供大家拷贝直接使用。本文出自CSDN-固本培元。转载注明出处-leoluopy@gmail.com。
应用思路注意事项:
共享内存:
#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
http://blog.csdn.net/bxhj3014/article/details/2082255
http://blog.csdn.net/liuchangyu23/article/details/4584045
boost进程间通信经常使用开发一篇全(消息队列,共享内存,信号)的更多相关文章
- iOS开发数据库篇—FMDB数据库队列
iOS开发数据库篇—FMDB数据库队列 一.代码示例 1.需要先导入FMDB框架和头文件,由于该框架依赖于libsqlite库,所以还应该导入该库. 2.代码如下: // // YYViewContr ...
- iOS开发——优化篇—— 25个性能优化/内存优化常用方法
1. 用ARC管理内存 ARC(Automatic ReferenceCounting, 自动引用计数)和iOS5一起发布,它避免了最常见的也就是经常是由于我们忘记释放内存所造成的内存泄露.它自动为你 ...
- asp.net微信开发第九篇----模板消息的使用
微信平台的模板消息,使用起来非常好,效果如下: 和平时我们微信中关注信用卡官方微信,如果消费了,信用卡官方微信就返回一个模板消息给我们告知,余额还有多少,消费了多少. 使用的步骤,我只简单介绍了怎么使 ...
- python【第十一篇】消息队列RabbitMQ、缓存数据库Redis
大纲 1.RabbitMQ 2.Redis 1.RabbitMQ消息队列 1.1 RabbitMQ简介 AMQP,即Advanced Message Queuing Protocol,高级消息队列协议 ...
- Android 开发笔记 “Android 的消息队列模型”
Android是参考Windows的消息循环机制来实现Android自身的消息循环的. Android通过Looper.Handler来实现消息循环机制,Android消息循环是针对线程的(每个线程都 ...
- windows 驱动开发 MDL 内核层 用户层共享内存
参考资料 https://blog.csdn.net/wdykanq/article/details/7752909 http://blog.51cto.com/laokaddk/404584 内核层 ...
- linux 进程间通信机制(IPC机制)一消息队列
消息队列提供了一种从一个进程向另一个进程发送一个数据块的方法.每个数据块都被认为含有一个类型,接收进程可以独立地接收含有不同类型的数据结构.我们可以通过发送消息来避免命名管道的同步和阻塞问题.但是消息 ...
- 【windows 操作系统】进程间通信(IPC)简述|无名管道和命名管道 消息队列、信号量、共享存储、Socket、Streams等
一.进程间通信简述 每个进程各自有不同的用户地址空间,任何一个进程的全局变量在另一个进程中都看不到,所以进程之间要交换数据必须通过内核,在内核中开辟一块缓冲区,进程1把数据从用户空间拷到内核缓冲区,进 ...
- v76.01 鸿蒙内核源码分析(共享内存) | 进程间最快通讯方式 | 百篇博客分析OpenHarmony源码
百篇博客分析|本篇为:(共享内存篇) | 进程间最快通讯方式 进程通讯相关篇为: v26.08 鸿蒙内核源码分析(自旋锁) | 当立贞节牌坊的好同志 v27.05 鸿蒙内核源码分析(互斥锁) | 同样 ...
随机推荐
- 求n阶勒让德多项式
Time Limit: 1 Sec Memory Limit: 128 MB Submit: 161 Solved: 105 [Submit][Status][Web Board] Descrip ...
- HDU 1864最大报销额(一维背包)
题目地址:HDU 1864 刚上来看着挺麻烦的..细致看了看原来好简单好简单...仅仅要去掉一些不符合要求的发票,剩下的就是最简单的背包问题了..对于小数问题,仅仅要*100就变成整数了. 代码例如以 ...
- [原创].NET 分布式架构开发实战五 Framework改进篇
原文:[原创].NET 分布式架构开发实战五 Framework改进篇 .NET 分布式架构开发实战五 Framework改进篇 前言:本来打算这篇文章来写DAL的重构的,现在计划有点改变.之前的文章 ...
- zoj 3696 Alien's Organ(泊松分布)
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3696 Alien's Organ Time Limit: 2 S ...
- Socket编程实践(4) --更复杂的过程server
1.Socket地址复用 int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen); in ...
- 猪和python(pig and python)
Python 真是无处不在国内. pig 0.9后python作为嵌入式语音,采用Jython解释器使用python2.5特征,此接口是最上层org.apache.pig.scripting.Pig首 ...
- Windowsport80解决方案被占用
今天,在一个非常沮丧的实施Server什么时候,一个错误port80占用.因此,找到一种方法来解决各类.最后,我的解决方案列出的问题来,要遇到的人做一些参考同样的问题. 第一步,找出哪些程序正在使用p ...
- SQL于union, EXCEPT 和 INTERSECT用法
这三个放在一起是有道理的,因为它们运行两个或两个以上的结果集,而这些结果对例如设置以下限制: 列的数目和所有查询必须是相同的列顺序. 数据类型必须兼容. 而且它们都是处理于多个结果集中有反复数据的 ...
- Python网络02 Python服务器进化
原文:Python网络02 Python服务器进化 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! **注意,在Python 3. ...
- ORACLE安装心得,大家一起分享,假设不正确的地方,大家请指出来
1. 安装\Oracle\10201_database_win32.zip: a) 安装图解: http://jingyan.baidu.com/article/5d6edee228308899ead ...