SERVER
int shareMem()
{
HANDLE hShareMem;
LPVOID pMem;
/*
MSDN:
Return value
If the function succeeds, the return value is a handle to the newly created file mapping object.
If the object exists before the function call, the function returns a handle to the existing object
(with its current size, not the specified size), and GetLastError returns ERROR_ALREADY_EXISTS.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
*/
hShareMem = CreateFileMapping( INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0, //文件共享的大小高位字节 32位机设0
1024, //文件共享的大小低位字节
"SHARE" //共享文件对象名称
);
if( !hShareMem)
{
return -1;
}
pMem = MapViewOfFile( hShareMem, //共享对象
FILE_MAP_ALL_ACCESS,//文件共享属性
0, //文件共享区的高位偏移地址
0, //文件共享区的低位偏移地址
0 //共享数据长度 全部共享设0
);
while(1)
{
strcpy( (char*)pMem,"Hello!\n");
Sleep(100);
}
CloseHandle(hShareMem);
return 0;
}
client
void getShareMem()
{
HANDLE hShareMem;
LPVOID pMem;
/*
MSDN:
Return value
If the function succeeds, the return value is an open handle to the specified file mapping object.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
*/
hShareMem = OpenFileMapping( FILE_MAP_READ | FILE_MAP_WRITE,
TRUE,
"SHARE"
);
if( !hShareMem )
{
return -1;
}
pMem = MapViewOfFile( hShareMem,
FILE_MAP_READ | FILE_MAP_WRITE,
0,
0,
0
);
while(1)
{
printf("%s",pMem);
Sleep(1000);
}
UnmapViewOfFile(pMem);
CloseHandle(hShareMem);
}