Wednesday, March 28, 2007

Shared memory in Windows...

Shared memory Server

#include <stdio.h>
#include <conio.h>
#include <windows.h>

int main(int argc, char* argv[])
{

HANDLE hMemMapFile;
LPSTR lpMsg;

hMemMapFile = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,
PAGE_READWRITE,0,0x1000,"SharedMemory");


if(hMemMapFile == NULL)
{
printf("n Failed to allocate Shared memory...");
exit(1);
}
lpMsg = (LPSTR)MapViewOfFile(hMemMapFile,FILE_MAP_WRITE,0,0,0);

if(lpMsg == NULL)
{
printf("n Failed to map shared memory ...");
exit(1);

}
lpMsg[0] = NULL;

while(lpMsg[0] == NULL) Sleep(1000);

printf("n Message Received : %s",lpMsg);

UnmapViewOfFile(lpMsg);


getch();
return 0;
}

Shared memory Client :

#include <stdio.h>
#include <conio.h>
#include <windows.h>

int main(int argc, char* argv[])
{

HANDLE hMemMapFile;
LPSTR lpMsg;

hMemMapFile = CreateFileMapping((HANDLE)0xffffffff,NULL,PAGE_READWRITE,0,0x1000,"SharedMemory");

if(hMemMapFile == NULL)
{
printf("n Failed to allocate Shared memory...");
exit(1);
}
lpMsg = (LPSTR)MapViewOfFile(hMemMapFile,FILE_MAP_WRITE,0,0,0);

if(lpMsg == NULL)
{
printf("n Failed to map shared memory ...");
exit(1);
}


strcpy(lpMsg,"Hello from client");
printf("n Message sent from client :%s",lpMsg);
UnmapViewOfFile(lpMsg);
getch();
return 0;
}


0 Comments:

Post a Comment

<< Home