CreateFileMapping MapViewOfFile

时间:2010-04-12 15:23:12

标签: c++ windows winapi

使用win32api,我希望以下程序创建两个进程并创建一个文件映射。 (使用c ++)

我不知道我应该在Handle CreateFileMapping(...写些什么。 我试过了:

PROCCESS_INFORMATION hfile.

此外,第一个参数应为INVALID_HANDLE_VALUE,但后来我不知道将MapViewOfFile写入第一个参数的内容。

来自第一个程序的代码:(我没有编写2.& 3.因为即使第一个程序也不起作用)

//Initial process creates proccess 2 and 3 

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

void main()
{

bool ret;
bool retwait;
bool bhandleclose;

STARTUPINFO startupinfo;
GetStartupInfo (&startupinfo);

PROCESS_INFORMATION pro2info;
PROCESS_INFORMATION pro3info;

//create proccess 2
wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA2pro2.exe";


 ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
  NULL, &startupinfo, &pro2info);


 if (ret==false){
  cout<<"Prozess konnte nicht erzeugt werden. Fehler:"<<GetLastError();
  ExitProcess(0);
 }

 //***************


 //create process3

wchar_t wcs2CommandLine[] = L"D:\\betriebssystemePRA2pro3.exe";


 ret = CreateProcess(NULL, wcs2CommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
  NULL, &startupinfo, &pro3info);


 if (ret==false){
  cout<<"Prozess konnte nicht erzeugt werden. Fehler:"<<GetLastError();
  ExitProcess(0);
 }



 //***************



 //create mapping object 

 // program2:




 PROCESS_INFORMATION hfile;





  CreateFileMapping(  //erzeugt filemapping obj  returned ein handle
  INVALID_HANDLE_VALUE, //mit dem handle-->kein seperates file nötig
  NULL,
  PAGE_READWRITE,  //rechte (lesen&schreiben)
  0,
  5,
  L"myfile");  //systemweit bekannter name


    LPVOID mappointer = MapViewOfFile( //virtuelle speicherraum, return :zeiger, der auf den bereich zeigt
  INVALID_HANDLE_VALUE, //handle des filemappingobj.
  FILE_MAP_ALL_ACCESS,
  0,
  0,
  100);



    //wait
    cout<<"beliebige Taste druecken"<<endl;
    cin.get();


//close


 bool unmap;

 unmap = UnmapViewOfFile (mappointer);

 if (unmap==true)
  cout<<"Unmap erfolgreich"<<endl;
 else
  cout<<"Unmap nicht erfolgreich"<<endl;


 bhandleclose=CloseHandle (INVALID_HANDLE_VALUE);
 cout<<bhandleclose<<endl;

 bhandleclose=CloseHandle (pro2info.hProcess);
 bhandleclose=CloseHandle (pro3info.hProcess);


 ExitProcess(0);


}

2 个答案:

答案 0 :(得分:2)

MapViewOfFile获取CreateFileMapping返回的句柄:

HANDLE hFileMapping = CreateFileMapping(...);
LPVOID lpBaseAddress = MapViewOfFile(hFileMapping, ...);

答案 1 :(得分:1)

您需要将CreateFileMapping的返回值作为MapViewOfFile的第一个参数传递。此外,MapViewOfFile中要映射的字节数应足够小,以使视图不长于文件本身。

HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
                                    0, 5, L"myfile");

LPVOID mappointer = MapViewOfFile(hMapping, FILE_MAP_ALL_ACCESS, 0, 0, 5);