#include <windows.h>
#include <tchar.h>
#include <stdio.h>
unsigned int getpnnum(HANDLE *phandle);
BOOL refresh(unsigned int num, HANDLE file);
unsigned int read_num(HANDLE file);
TCHAR p_inf[] = _T("NUMBER");
unsigned int getpnnum(HANDLE *phandle)
{
unsigned int r = 0;
HANDLE handle = NULL;
handle = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, p_inf);
if (handle != NULL)
{
r = read_num(handle);
refresh(r + 1, handle);
*phandle = handle;
return r + 1;
}
else
{
handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
0, sizeof(unsigned int), p_inf);
if (handle != NULL)
printf("内存映射文件建立成功!\n");
refresh(1, handle);
*phandle = handle;
return 1;
}
}
BOOL refresh(unsigned int num, HANDLE file)
{
unsigned int*temp = NULL;
if (file != NULL)
{
temp = (unsigned int*)MapViewOfFile(file,
FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (temp != NULL)
{
*temp = num;UnmapViewOfFile(temp);
}
else return FALSE;
return TRUE;
}
else return FALSE;
}
/*读内存映射区*/
unsigned int read_num(HANDLE file)
{
unsigned int*temp = NULL;
unsigned int r = 0;
if (file != NULL)
{
temp = (unsigned int*)MapViewOfFile(file,
FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (temp != NULL)
{
r = *temp;UnmapViewOfFile(temp);return r;
}
else return 0;
}
else
return 0;
}
int main()
{
HANDLE hPIN_num = NULL; /*实例节点数目内存映射*/
unsigned int num = 0, th;
th = getpnnum(&hPIN_num);
printf("这是第%d个PINode实例\n", th);
while (1);
th = read_num(hPIN_num);
refresh(th - 1, hPIN_num);
CloseHandle(hPIN_num);
return 0;
}
CreateFileMapping
最新推荐文章于 2024-01-05 07:15:00 发布