#include #include HANDLE hMapFile; LPVOID lpMapAddress; HANDLE hEventAccess; LPCSTR fEventProd="Access"; /************************************************************************ * void ErrorOut(LPSTR errstring) * * Purpose: Print out an meainful error code by means of * GetLastError and printf * * Inputs: errstring - the action that failed, passed by the * calling proc. * * Returns: none * * Calls: GetLastError * \************************************************************************/ void ErrorOut(LPSTR errstring) { MessageBox(NULL, errstring, NULL, MB_OK); } /************************************************************************** * HANDLE CreateMap(HANDLE FileToBeMapped, char *MapName ) * * Purpose: Create File Mapping object using the open file handle * * Inputs: FileToBeMapped - handle to the file * * Returns: MapHandle - handle to the file mapping object * or NULL if failure * * Calls: CreateFileMapping, ErrorOut \**************************************************************************/ HANDLE CreateMap(HANDLE FileToBeMapped, LPSTR MapName) { HANDLE MapHandle; MapHandle= CreateFileMapping(FileToBeMapped, NULL, PAGE_READWRITE, 0, 4096, MapName); if (MapHandle == NULL) { ErrorOut("CreateFileMapping"); return(NULL); } else return(MapHandle); } /************************************************************************** * LPVOID MapView(HANDLE hMap) * * Purpose: Map the file mapping object into address space * * Inputs: hMap - handle to the mapping object * * Returns: MappedPointer - pointer to the address space that the * object is mapped into * or NULL if failure * * Calls: MapViewOfFile, ErrorOut * \**************************************************************************/ LPVOID MapView(HANDLE hMap) { LPVOID MappedPointer; MappedPointer= MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 4096); if (MappedPointer == NULL) { ErrorOut("MapViewOfFile"); return(NULL); } else return(MappedPointer); } LPVOID ReadBytes(LPVOID from, LPVOID to, DWORD len) { return(memcpy(to,from,len)); } LPVOID WriteBytes(LPVOID to, LPVOID from, DWORD len) { return(memcpy(to,from,len)); } int main() { MessageBox(NULL,"Consumer started","Consumer",MB_OK); hEventAccess=CreateEvent(NULL,FALSE,FALSE,"Access"); hMapFile = CreateMap((HANDLE) 0xFFFFFFFF, "Warehouse"); lpMapAddress = MapView(hMapFile); int crt_items; for(;;) { Sleep(rand()/100); WaitForSingleObject(hEventAccess, INFINITE); ReadBytes(lpMapAddress, &crt_items, sizeof(int)); if (crt_items>0) { crt_items--; WriteBytes(lpMapAddress, &crt_items, sizeof(int)); printf("Consumed 1 item\n"); } else printf("No items in stock\n"); SetEvent(hEventAccess); } //cleanup UnmapViewOfFile(lpMapAddress); CloseHandle(hMapFile); return 0; }