首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

共享内存的例证(转msdn)

2012-08-21 
共享内存的例子(转msdn)#include windows.h#include stdio.h#include conio.h#define BUF_SIZE 256T

共享内存的例子(转msdn)

#include <windows.h>#include <stdio.h>#include <conio.h>#define BUF_SIZE 256TCHAR szName[]=TEXT("Global\\MyFileMappingObject");TCHAR szMsg[]=TEXT("Message from first process");int main(){ HANDLE hMapFile; LPCTSTR pBuf; hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // max. object size BUF_SIZE, // buffer size szName); // name of mapping object if (hMapFile == NULL) { printf("Could not create file mapping object (%d).\n", GetLastError()); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { printf("Could not map view of file (%d).\n", GetLastError()); return 2; } CopyMemory((PVOID)pBuf, szMsg, strlen(szMsg)); _getch(); UnmapViewOfFile(pBuf); CloseHandle(hMapFile); return 0;}?

Second Process

#include <windows.h>#include <stdio.h>#include <conio.h>#define BUF_SIZE 256TCHAR szName[]=TEXT("Global\\MyFileMappingObject");int main(){   HANDLE hMapFile;   LPCTSTR pBuf;   hMapFile = OpenFileMapping(                   FILE_MAP_ALL_ACCESS,   // read/write access                   FALSE,                 // do not inherit the name                   szName);               // name of mapping object     if (hMapFile == NULL)    {       printf("Could not open file mapping object (%d).\n",              GetLastError());      return 1;   }     pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object               FILE_MAP_ALL_ACCESS,  // read/write permission               0,                                   0,                                   BUF_SIZE);                       if (pBuf == NULL)    {       printf("Could not map view of file (%d).\n",              GetLastError());       return 2;   }   MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);   UnmapViewOfFile(pBuf);   CloseHandle(hMapFile);    return 0;}
?

这个例子的意思是,进程1开一个叫"Global\\MyFileMappingObject"的共享内存,然后把一片数据"Message from first process"拷到共享内存里面,然后等待用户的_getch()。这时,进程2开始运行,它以相同的名字"Global\\MyFileMappingObject"打开共享内存,把进程1放在里面的数据"Message from first process"读出来,然后退出。接着用户实施_getch(),进程1也退出,共享内存被撤销。

热点排行