进程间动态对象共享

来源:互联网 发布:淘宝爆款采集软件 编辑:程序博客网 时间:2024/06/02 06:06

设想:在两个子进程之间共享类实例

 

说明:前几天要写一个多进程的服务程序,用到了一个日志类记录程序的运行情况,日志类用到了单态保证只有一个对象存在。后来想到如果要在两个子进程之间共享一个普通的类对象,该用什么方法。于是做了一个试验,尝试一下。


试验中用到了两个比较重要的概念,由于我对此不是很了解,就在网上找到了两篇文章分别学习了一下,以下是文章的链接,如果需要,可以仔细研究一下:

宋久擎:关于C++中new的深入探讨 http://blog.csdn.net/songthin/archive/2007/07/23/1703966.aspx

郑彦兴:Linux 进程间通信:共享内存 http://blog.csdn.net/realone78/archive/2008/08/29/2846747.aspx

 

我的思路是这样,在程序代码中,主函数首先创建一块共享内存,然后用C++ new的定位构造功能,在这块申请的共享内存中创建并且初始化一个类对象,这样 ,在子进程中就可以使用这个内存区域的类实例。

 

以下是验证用得代码,结果是正确的但是不知道是否符合规范:

 

  1. #include <iostream>
  2. #include <unistd.h>   
  3. #include <sys/types.h>   
  4. #include <string>   
  5. #include <stdlib.h>   
  6. #include <fcntl.h>
  7. #include <sys/mman.h>
  8. #include <string>
  9. #include <new>
  10. #define N (1)
  11. using namespace std;
  12. class A{
  13.     char content[200];
  14.     int i;
  15. public
  16.     A(int j){ content[0]=0;i=j;cout<<"Construct class A"<<endl;};
  17.     void Say()
  18.     { 
  19.         cout<<"Information from father: ";
  20.         cout<<"i="<<i<<";content="<<content<<endl;
  21.     };
  22.     void Set(int j){ i=j;};
  23.     void Set(const char* p){ strcpy(content,p);};
  24. };
  25. main(int argc, char** argv)
  26. {
  27.     int i;
  28.     A *p_map;
  29.     char temp;
  30.     p_map=(A*)mmap(NULL,sizeof(A)*N,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);
  31.     if(fork() == 0)
  32.     {
  33.         sleep(1);
  34.         A* p=(A*)p_map;
  35.         p->Say();
  36.         munmap(p_map,sizeof(A)*N); 
  37.         exit(0);
  38.     }
  39.     new(p_map) A(67);//在 p_map 处构造一个A对象
  40.     p_map->Set(11);
  41.     p_map->Set("/"Hello child, I am father!/"");
  42.     sleep(2);
  43.     printf("umap/n");
  44.     munmap( p_map,sizeof(A)*N );
  45.     printf( "umap ok/n" );
  46. }

 

运行结果是

 LeoS:~/project/proc$ ./a.out

Construct class A
Information from father: i=11;content="Hello child, I am father!"
umap
umap ok