您的位置:首页 > 编程语言 > C语言/C++

VC中进程间共享内存实现

2013-08-26 13:52 197 查看
VC++6.0共享内存技术总结

程序1 -- 建立共享区,写数据:

Cpp代码

int main(int argc, char* argv[])  

{  

 HANDLE lhShareMemory;  

 char* lpBuffer = NULL;  

   

 lhShareMemory = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE,  

  0, 10, "mySharedMemory");  

   

 if (NULL == lhShareMemory)  

 {  

   if (ERROR_ALREADY_EXISTS == GetLastError())  

  
{  

   
cout << "Already exists!";  

  
}  

   else  

  
{  

   
cout << "Create Sheared Memory unsuccessfully!";  

   }  

   return 0;  

 }  

   

 lpBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_WRITE, 0, 0, 10);  

 if (NULL == lpBuffer)  

 {  

  
cout << "Get Share memory unsuccessfully!";  

   return 0;  

 } 

 strcpy(lpBuffer, "hello"); 

 cout << "进程通信:采用共享内存" << endl;  

 cout << "写进程" << endl; 

 cout << "写入数据:"<< endl<<lpBuffer << endl;  

 Sleep(100000);  

 UnmapViewOfFile(lpBuffer);

 return 0; 

}  

   

程序2 -- 使用共享区,读数据:

Cpp代码

int main(int argc, char* argv[])  

{  

  HANDLE lhShareMemory;  

  char* lpcBuffer;  

   

  lhShareMemory = OpenFileMapping(FILE_MAP_READ, false, "mySharedMemory");  

  if (NULL == lhShareMemory)  

  {  

  
cout << "Open share memory unsuccessfully!" << endl;  

   DWORD ldwError = GetLastError();  

  
cout << ldwError;  

   return 0;  

  }  

   

  lpcBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_READ, 0, 0, 100);  

  if (NULL == lpcBuffer)  

  {  

  
cout << "Open share memory unsuccessfully!";  

   return 0;  

  }  

  cout << "进程通信:采用共享内存" << endl;  

  cout << "读进程" << endl;  

  cout << "读入数据:" << endl;  

  for (int i = 0; i < 100; ++i)  

  {  

  
cout << *(lpcBuffer + i);  

 
}   

 UnmapViewOfFile(lpcBuffer); 

 return 0;  
<
9b5c
li style="padding-bottom:0px;border-right-width:0px;list-style-type:decimal;margin:0px 0px 0px 30px;padding-left:0px;padding-right:0px;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;">
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vc++ 通信 内存