boost進程間通信經常使用開發一篇全(消息隊列,共享內存,信號)


本文概要:

        敏捷開發大家想必知道並且評價甚高,縮短開發周期,提高開發質量。將大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



參考文章:

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










免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM