在普通应用程序中使用共享内存方式创建内存共享对象时,CreateFileMapping函数总是返回句柄为NULL,通过GetLastError得到返回错误码 0x5, 问题解决:
使用Local 代替Global, 问题解决,下面是使用实例:
TCHAR szName[] = TEXT("Local\\MyFileMappingObject");
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
原来 Global\\ 保证创建的对象是全局的,对权限要求比较高,而使用local可以保证服务对象仅对当前用户中的进程和线程可见。这就是总是返回权限失败问题的原因。
附一个使用实例:
// testsharemem.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
#include
#include
#define BUF_SIZE 256
TCHAR szName[] = TEXT("Local\\MyFileMappingObject");
TCHAR szMsg[] = TEXT("Message from first process.");
int p1();
int p2();
int _tmain(int argc, _TCHAR* argv[])
{
if (argc == 1)
{
p1();
}
else
{
p2();
}
return 0;
}
int p1()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("P1: Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
else
{
_tprintf(TEXT("P1: create file mapping object hMapFile= (0x%x).\n", hMapFile));
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("P1: Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
int p2()
{
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)
{
_tprintf(TEXT("P2: 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)
{
_tprintf(TEXT("P2: Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}