当前位置: 首页>>代码示例>>C++>>正文


C++ MapViewOfFile函数代码示例

本文整理汇总了C++中MapViewOfFile函数的典型用法代码示例。如果您正苦于以下问题:C++ MapViewOfFile函数的具体用法?C++ MapViewOfFile怎么用?C++ MapViewOfFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了MapViewOfFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: Entry

    MMap::MMap (const Entry& entry, bool readwrite, bool preload, int64_t mapped_size) :
      Entry (entry), addr (NULL), first (NULL), msize (mapped_size), readwrite (readwrite)
    {
      DEBUG (std::string (readwrite ? "creating RAM buffer for" : "memory-mapping" ) + " file \"" + Entry::name + "\"...");

      struct stat sbuf;
      if (stat (Entry::name.c_str(), &sbuf))
        throw Exception ("cannot stat file \"" + Entry::name + "\": " + strerror (errno));

      mtime = sbuf.st_mtime;


      if (msize < 0) 
        msize = sbuf.st_size - start;
      else if (start + msize > sbuf.st_size) 
        throw Exception ("file \"" + Entry::name + "\" is smaller than expected");

      if (readwrite) {
        try {
          first = new uint8_t [msize];
          if (!first) throw 1;
        }
        catch (...) {
          throw Exception ("error allocating memory to hold mmap buffer contents");
        }

        if (preload) {
          CONSOLE ("preloading contents of mapped file \"" + Entry::name + "\"...");
          std::ifstream in (Entry::name.c_str(), std::ios::in | std::ios::binary);
          if (!in) 
            throw Exception ("failed to open file \"" + Entry::name + "\": " + strerror (errno));
          in.seekg (start, in.beg);
          in.read ((char*) first, msize);
          if (!in.good())
            throw Exception ("error preloading contents of file \"" + Entry::name + "\": " + strerror(errno));
        }
        else 
          memset (first, 0, msize);
        DEBUG ("file \"" + Entry::name + "\" held in RAM at " + str ( (void*) first) + ", size " + str (msize));
      }
      else {

        if ( (fd = open (Entry::name.c_str(), O_RDONLY, 0666)) < 0)
          throw Exception ("error opening file \"" + Entry::name + "\": " + strerror (errno));

        try {
#ifdef MRTRIX_WINDOWS
          HANDLE handle = CreateFileMapping ( (HANDLE) _get_osfhandle (fd), NULL,
              PAGE_READONLY, 0, start + msize, NULL);
          if (!handle) throw 0;
          addr = static_cast<uint8_t*> (MapViewOfFile (handle, FILE_MAP_READ, 0, 0, start + msize));
          if (!addr) throw 0;
          CloseHandle (handle);
#else
          addr = static_cast<uint8_t*> (mmap ( (char*) 0, start + msize,
                PROT_READ, MAP_PRIVATE, fd, 0));
          if (addr == MAP_FAILED) throw 0;
#endif
        }
        catch (...) {
          close (fd);
          addr = NULL;
          throw Exception ("memory-mapping failed for file \"" + Entry::name + "\": " + strerror (errno));
        }
        first = addr + start;

        DEBUG ("file \"" + Entry::name + "\" mapped at " + str ( (void*) addr) + ", size " + str (msize)
            + " (read-" + (readwrite ? "write" : "only") + ")");
      }
    }
开发者ID:JohnWangDataAnalyst,项目名称:mrtrix3,代码行数:70,代码来源:mmap.cpp

示例2: WNInstall_MoveFileOnReboot

bool WNInstall_MoveFileOnReboot(const char * pszExisting, const char * pszNew)
{	
  bool fOk = 0;
#if !JDK_IS_WINE   
  HMODULE hLib=LoadLibrary("kernel32.dll");
  if (hLib)
  {
    typedef BOOL (WINAPI *mfea_t)(LPCSTR lpExistingFileName,LPCSTR lpNewFileName,DWORD dwFlags);
    mfea_t mfea;
    mfea=(mfea_t) GetProcAddress(hLib,"MoveFileExA");
    if (mfea)
    {
      fOk=(mfea(pszExisting, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)!=0);
    }
    FreeLibrary(hLib);
  }

  if (!fOk)
  {
    static char szRenameLine[1024];
    int cchRenameLine;
    char *szRenameSec = "[Rename]\r\n";
    HANDLE hfile, hfilemap;
    DWORD dwFileSize, dwRenameLinePos=0;
    static char wininit[1024];
    static char tmpbuf[1024];
    static char nulint[4]="NUL";

    if (pszNew) GetShortPathName(pszNew,tmpbuf,1024);
    else *((int *)tmpbuf) = *((int *)nulint);
    // wininit is used as a temporary here
    GetShortPathName(pszExisting,wininit,1024);
    pszExisting=wininit;
    cchRenameLine = wsprintf(szRenameLine,"%s=%s\r\n",tmpbuf,pszExisting);

    GetWindowsDirectory(wininit, 1024-16);
    lstrcat(wininit, "\\wininit.ini");
    hfile = CreateFile(wininit,
        GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);

    if (hfile != INVALID_HANDLE_VALUE) 
    {
      dwFileSize = GetFileSize(hfile, NULL);
      hfilemap = CreateFileMapping(hfile, NULL, PAGE_READWRITE, 0, dwFileSize + cchRenameLine + 10, NULL);

      if (hfilemap != NULL) 
      {
        LPSTR pszWinInit = (LPSTR) MapViewOfFile(hfilemap, FILE_MAP_WRITE, 0, 0, 0);

        if (pszWinInit != NULL) 
        {
          int do_write=0;
          LPSTR pszRenameSecInFile = strstr(pszWinInit, szRenameSec);
          if (pszRenameSecInFile == NULL) 
          {
            lstrcpy(pszWinInit+dwFileSize, szRenameSec);
            dwFileSize += 10;
            dwRenameLinePos = dwFileSize;
            do_write++;
          } 
          else
          {
            char *pszFirstRenameLine = strstr(pszRenameSecInFile, "\n")+1;
            int l=pszWinInit + dwFileSize-pszFirstRenameLine;
            if (!wninstall_findinmem(pszFirstRenameLine,szRenameLine,l))
            {
              memmove(pszFirstRenameLine + cchRenameLine, pszFirstRenameLine, l);
              dwRenameLinePos = pszFirstRenameLine - pszWinInit;
              do_write++;
            }
          }

          if (do_write)
          {
            memcpy(&pszWinInit[dwRenameLinePos], szRenameLine,cchRenameLine);
            dwFileSize += cchRenameLine;
          }

          UnmapViewOfFile(pszWinInit);

          fOk++;
        }
        CloseHandle(hfilemap);
      }
      SetFilePointer(hfile, dwFileSize, NULL, FILE_BEGIN);
      SetEndOfFile(hfile);
      CloseHandle(hfile);
    }
  }
#endif
  return fOk;
	
}
开发者ID:jdkoftinoff,项目名称:if2kv2,代码行数:94,代码来源:wninstall.cpp

示例3: main

int main(int argc, char **argv)
{
struct gtkwave_dual_ipc_t *dual_ctx;
char buf[257], buf2[257];
int shmid;
GtkWidget *main_vbox, *mainwindow, *vpan;
int i;
int split_point = -1;
#ifdef __MINGW32__
char mapName[65];
HANDLE hMapFile;
#endif

GtkWidget *xsocket[2] = { NULL, NULL };

WAVE_LOCALE_FIX

if(!gtk_init_check(&argc, &argv))
        {
        printf("Could not initialize GTK!  Is DISPLAY env var/xhost set?\n\n");
	exit(255);
        }

#ifdef __CYGWIN__
fprintf(stderr, "TWINWAVE| If the viewer crashes with a Bad system call error,\n");
fprintf(stderr, "TWINWAVE| make sure that Cygserver is enabled.\n");
#endif

for(i=0;i<argc;i++)
	{
	if(!strcmp(argv[i], "+"))
		{
		split_point = i;
		break;
		}

	if(!strcmp(argv[i], "++"))
		{
		split_point = i;
		use_embedded = 0;
		break;
		}
	}

if(split_point < 0)
	{
	printf("Usage:\n------\n%s arglist1 separator arglist2\n\n"
		"The '+' between argument lists splits and creates one window.\n"
		"The '++' between argument lists splits and creates two windows.\n"
		"\n", argv[0]);
	exit(255);
	}

mainwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Initializing");
#ifndef MAC_INTEGRATION
gtk_widget_set_usize(GTK_WIDGET(mainwindow), 820, 800);
#else
gtk_widget_set_usize(GTK_WIDGET(mainwindow), 400,32); /* quartz doesn't retarget into mainwindow */
#endif
gtk_widget_show(mainwindow);

gtk_signal_connect(GTK_OBJECT(mainwindow), "destroy", GTK_SIGNAL_FUNC(quit_callback), "WM destroy");


xsocket[0] = gtk_socket_new ();
xsocket[1] = gtk_socket_new ();
gtk_widget_show (xsocket[0]);
gtk_widget_show (xsocket[1]);

gtk_signal_connect(GTK_OBJECT(xsocket[0]), "plug-removed", GTK_SIGNAL_FUNC(plug_removed), NULL);

main_vbox = gtk_vbox_new(FALSE, 5);
gtk_container_border_width(GTK_CONTAINER(main_vbox), 1);
gtk_container_add(GTK_CONTAINER(mainwindow), main_vbox);
gtk_widget_show(main_vbox);

vpan = gtk_vpaned_new ();
gtk_widget_show (vpan);
gtk_box_pack_start (GTK_BOX (main_vbox), vpan, TRUE, TRUE, 1);

gtk_paned_pack1 (GTK_PANED (vpan), xsocket[0], TRUE, FALSE);

gtk_signal_connect(GTK_OBJECT(xsocket[1]), "plug-removed", GTK_SIGNAL_FUNC(plug_removed), NULL);

gtk_paned_pack2 (GTK_PANED (vpan), xsocket[1], TRUE, FALSE);

#ifdef __MINGW32__
shmid = getpid();
sprintf(mapName, "twinwave%d", shmid);
hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 2 * sizeof(struct gtkwave_dual_ipc_t), mapName);
if(hMapFile != NULL)
        {
        dual_ctx = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 2 * sizeof(struct gtkwave_dual_ipc_t));

        if(dual_ctx)
               	{
               	memset(dual_ctx, 0, 2 * sizeof(struct gtkwave_dual_ipc_t));
               	memcpy(&dual_ctx[0].matchword, DUAL_MATCHWORD, 4);
               	memcpy(&dual_ctx[1].matchword, DUAL_MATCHWORD, 4);
//.........这里部分代码省略.........
开发者ID:Pidbip,项目名称:egtkwave,代码行数:101,代码来源:twinwave.c

示例4: SSQ_Init

int		SSQ_Init(SS_QUEUE_OBJ_T *pObj, unsigned int sharememory, unsigned int channelid, wchar_t *sharename, unsigned int bufsize, unsigned int prerecordsecs, unsigned int createsharememory)
{
	wchar_t wszHeaderName[36] = {0,};
	wchar_t wszFramelistName[36] = {0,};
	wchar_t wszDataName[36] = {0,};
	if (NULL==pObj)											return -1;
	if (createsharememory==0x01 && bufsize<1)				return -1;
	if ( (sharememory==0x01) && (NULL==sharename || (0==wcscmp(sharename, TEXT("\0")))) )	return -1;

	memset(pObj, 0x00, sizeof(SS_QUEUE_OBJ_T));
	pObj->channelid = channelid;
	pObj->shareinfo.id = channelid;
	wcscpy(pObj->shareinfo.name, sharename);

	wchar_t wszMutexName[36] = {0,};
	wsprintf(wszMutexName, TEXT("%s%d_mutex"), sharename, channelid);
	pObj->hMutex = OpenMutex(NULL, FALSE, wszMutexName);
	if (NULL == pObj->hMutex)
	{
		pObj->hMutex = CreateMutex(NULL, FALSE, wszMutexName);
		if (NULL == pObj->hMutex)							return -1;
	}

	//Create Header map
	
	
#ifdef _WIN32
	if (sharememory == 0x01)
	{
		wsprintf(wszHeaderName, TEXT("%s%d_h"), sharename, channelid);
		pObj->hSSHeader = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszHeaderName);
		if (NULL==pObj->hSSHeader && createsharememory==0x01)
		{
			pObj->hSSHeader = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, sizeof(SS_HEADER_T), wszHeaderName);
			if (NULL==pObj->hSSHeader || pObj->hSSHeader==INVALID_HANDLE_VALUE)
			{
				return -1;
			}
		}
		pObj->pQueHeader = (SS_HEADER_T*)MapViewOfFile(pObj->hSSHeader, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0);
		if (createsharememory==0x01)
		{
			if (pObj->pQueHeader->bufsize < 1)
			{
				memset(pObj->pQueHeader, 0x00, sizeof(SS_HEADER_T));
				pObj->pQueHeader->bufsize = bufsize;
			}
		}
		else if (NULL==pObj->pQueHeader)
		{
			return -1;
		}
		else
		{
			bufsize = pObj->pQueHeader->bufsize;
 		}
	}
	else
	{
		pObj->pQueHeader = new SS_HEADER_T;
		memset(pObj->pQueHeader, 0x00, sizeof(SS_HEADER_T));
	}

	//==========================================
	//Create frame list map
	if (prerecordsecs > 0)
	{
		wsprintf(wszFramelistName, TEXT("%s%d_f"), sharename, channelid);
		unsigned int nFramelistNum = prerecordsecs * 30;	//每秒30帧
		unsigned int nFrameQueSize = nFramelistNum*sizeof(FRAMEINFO_LIST_T);

		if (sharememory == 0x01)
		{
			pObj->hSSFrameList = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszFramelistName);
			if (NULL==pObj->hSSFrameList && createsharememory==0x01)
			{
				pObj->hSSFrameList = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, nFrameQueSize, wszFramelistName);
				if (NULL==pObj->hSSFrameList || pObj->hSSFrameList==INVALID_HANDLE_VALUE)
				{
					return -1;
				}
			}
			pObj->pFrameinfoList = (FRAMEINFO_LIST_T*)MapViewOfFile(pObj->hSSFrameList, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0);
			if (createsharememory==0x01)
			{
				memset(pObj->pFrameinfoList, 0x00, nFrameQueSize);
				pObj->pQueHeader->framelistNum = nFramelistNum;
			}
			else if (NULL==pObj->hSSFrameList)
			{
				return -1;
			}
		}
		else
		{
			pObj->pFrameinfoList = new FRAMEINFO_LIST_T[nFramelistNum];
			memset(&pObj->pFrameinfoList[0], 0x00, sizeof(FRAMEINFO_LIST_T)*nFramelistNum);
			pObj->pQueHeader->framelistNum = nFramelistNum;
		}
	}
//.........这里部分代码省略.........
开发者ID:dong777,项目名称:EasyPlayer,代码行数:101,代码来源:ssqueue.cpp

示例5: caml_ba_map_file

CAMLprim value caml_ba_map_file(value vfd, value vkind, value vlayout,
                                value vshared, value vdim, value vstart)
{
  HANDLE fd, fmap;
  int flags, major_dim, mode, perm;
  intnat num_dims, i;
  intnat dim[MAX_NUM_DIMS];
  __int64 currpos, startpos, file_size, data_size;
  uintnat array_size, page, delta;
  char c;
  void * addr;
  LARGE_INTEGER li;
  SYSTEM_INFO sysinfo;

  fd = Handle_val(vfd);
  flags = Int_val(vkind) | Int_val(vlayout);
  startpos = Int64_val(vstart);
  num_dims = Wosize_val(vdim);
  major_dim = flags & BIGARRAY_FORTRAN_LAYOUT ? num_dims - 1 : 0;
  /* Extract dimensions from Caml array */
  num_dims = Wosize_val(vdim);
  if (num_dims < 1 || num_dims > MAX_NUM_DIMS)
    invalid_argument("Bigarray.mmap: bad number of dimensions");
  for (i = 0; i < num_dims; i++) {
    dim[i] = Long_val(Field(vdim, i));
    if (dim[i] == -1 && i == major_dim) continue;
    if (dim[i] < 0 || dim[i] > 0x7FFFFFFFL)
      invalid_argument("Bigarray.create: negative dimension");
  }
  /* Determine file size */
  currpos = caml_ba_set_file_pointer(fd, 0, FILE_CURRENT);
  if (currpos == -1) caml_ba_sys_error();
  file_size = caml_ba_set_file_pointer(fd, 0, FILE_END);
  if (file_size == -1) caml_ba_sys_error();
  /* Determine array size in bytes (or size of array without the major
     dimension if that dimension wasn't specified) */
  array_size = bigarray_element_size[flags & BIGARRAY_KIND_MASK];
  for (i = 0; i < num_dims; i++)
    if (dim[i] != -1) array_size *= dim[i];
  /* Check if the first/last dimension is unknown */
  if (dim[major_dim] == -1) {
    /* Determine first/last dimension from file size */
    if (file_size < startpos)
      failwith("Bigarray.mmap: file position exceeds file size");
    data_size = file_size - startpos;
    dim[major_dim] = (uintnat) (data_size / array_size);
    array_size = dim[major_dim] * array_size;
    if (array_size != data_size)
      failwith("Bigarray.mmap: file size doesn't match array dimensions");
  }
  /* Restore original file position */
  caml_ba_set_file_pointer(fd, currpos, FILE_BEGIN);
  /* Create the file mapping */
  if (Bool_val(vshared)) {
    perm = PAGE_READWRITE;
    mode = FILE_MAP_WRITE;
  } else {
    perm = PAGE_READONLY;       /* doesn't work under Win98 */
    mode = FILE_MAP_COPY;
  }
  li.QuadPart = startpos + array_size;
  fmap = CreateFileMapping(fd, NULL, perm, li.HighPart, li.LowPart, NULL);
  if (fmap == NULL) caml_ba_sys_error();
  /* Determine offset so that the mapping starts at the given file pos */
  GetSystemInfo(&sysinfo);
  delta = (uintnat) (startpos % sysinfo.dwPageSize);
  /* Map the mapping in memory */
  li.QuadPart = startpos - delta;
  addr = 
    MapViewOfFile(fmap, mode, li.HighPart, li.LowPart, array_size + delta);
  if (addr == NULL) caml_ba_sys_error();
  addr = (void *) ((uintnat) addr + delta);
  /* Close the file mapping */
  CloseHandle(fmap);
  /* Build and return the Caml bigarray */
  return alloc_bigarray(flags | BIGARRAY_MAPPED_FILE, num_dims, addr, dim);
}
开发者ID:avsm,项目名称:ocaml-community,代码行数:77,代码来源:mmap_win32.c

示例6: void

agent_pending_query *agent_query(
    strbuf *query, void **out, int *outlen,
    void (*callback)(void *, void *, int), void *callback_ctx)
{
    HWND hwnd;
    char *mapname;
    HANDLE filemap;
    unsigned char *p, *ret;
    int id, retlen;
    COPYDATASTRUCT cds;
    SECURITY_ATTRIBUTES sa, *psa;
    PSECURITY_DESCRIPTOR psd = NULL;
    PSID usersid = NULL;

    *out = NULL;
    *outlen = 0;

    if (query->len > AGENT_MAX_MSGLEN)
        return NULL;                   /* query too large */

    hwnd = FindWindow("Pageant", "Pageant");
    if (!hwnd)
	return NULL;		       /* *out == NULL, so failure */
    mapname = dupprintf("PageantRequest%08x", (unsigned)GetCurrentThreadId());

    psa = NULL;
#ifndef NO_SECURITY
    if (got_advapi()) {
        /*
         * Make the file mapping we create for communication with
         * Pageant owned by the user SID rather than the default. This
         * should make communication between processes with slightly
         * different contexts more reliable: in particular, command
         * prompts launched as administrator should still be able to
         * run PSFTPs which refer back to the owning user's
         * unprivileged Pageant.
         */
        usersid = get_user_sid();

        if (usersid) {
            psd = (PSECURITY_DESCRIPTOR)
                LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
            if (psd) {
                if (p_InitializeSecurityDescriptor
                    (psd, SECURITY_DESCRIPTOR_REVISION) &&
                    p_SetSecurityDescriptorOwner(psd, usersid, false)) {
                    sa.nLength = sizeof(sa);
                    sa.bInheritHandle = true;
                    sa.lpSecurityDescriptor = psd;
                    psa = &sa;
                } else {
                    LocalFree(psd);
                    psd = NULL;
                }
            }
        }
    }
#endif /* NO_SECURITY */

    filemap = CreateFileMapping(INVALID_HANDLE_VALUE, psa, PAGE_READWRITE,
				0, AGENT_MAX_MSGLEN, mapname);
    if (filemap == NULL || filemap == INVALID_HANDLE_VALUE) {
        sfree(mapname);
	return NULL;		       /* *out == NULL, so failure */
    }
    p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
    strbuf_finalise_agent_query(query);
    memcpy(p, query->s, query->len);
    cds.dwData = AGENT_COPYDATA_ID;
    cds.cbData = 1 + strlen(mapname);
    cds.lpData = mapname;

    /*
     * The user either passed a null callback (indicating that the
     * query is required to be synchronous) or CreateThread failed.
     * Either way, we need a synchronous request.
     */
    id = SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) &cds);
    if (id > 0) {
	retlen = 4 + GET_32BIT_MSB_FIRST(p);
	ret = snewn(retlen, unsigned char);
	if (ret) {
	    memcpy(ret, p, retlen);
	    *out = ret;
	    *outlen = retlen;
	}
    }
开发者ID:TortoiseGit,项目名称:TortoiseGit,代码行数:87,代码来源:WINPGNTC.C

示例7: InitializeSecurityDescriptor

	bool CShareMem::Create(std::string strSMName, unsigned unSMMSize)
	{
		bool bResult = false;
		do 
		{
			if(strSMName.empty() || 0 == unSMMSize || unSMMSize < sizeof(SWRPos))
				break;

			m_strSMName = strSMName;


			SECURITY_ATTRIBUTES SecAttr, *pSec = 0;
			SECURITY_DESCRIPTOR SecDesc;  
			if (strSMName.find("Global\\") != std::string::npos) 
			{     
				InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION);
				SetSecurityDescriptorDacl(&SecDesc, TRUE, (PACL)0, FALSE);  //Add the ACL to the security descriptor.这里设置的是一个空的DACL
				SecAttr.nLength = sizeof(SecAttr); 
				SecAttr.lpSecurityDescriptor = &SecDesc;  
				SecAttr.bInheritHandle = TRUE;  
				pSec = &SecAttr; 
			}


			std::string strMutexName = strSMName + "Mutex";
			m_hMutexSyncData = CreateMutexA(pSec, FALSE, strMutexName.c_str());
			if(NULL == m_hMutexSyncData)
				break;

			std::string strSemName = strSMName + "Recv";
			m_hWait[0] = CreateSemaphoreA(pSec, 0, 5000, strSemName.c_str());
			if(NULL == m_hWait[0])
				break;

			std::string strSemExit = strSMName + "Exit";
			m_hWait[1] = CreateSemaphoreA(pSec, 0, 1, strSemExit.c_str());
			if(NULL == m_hWait[0])
				break;


			//当你创建了一个命名管道,它的安全参数指定了NULL,这就表明只有创建者才可以作为Client访问这个命名管道。
			m_hFileMapObj = CreateFileMappingA(INVALID_HANDLE_VALUE, pSec, PAGE_READWRITE, 0, unSMMSize, strSMName.c_str());
			DWORD gg = GetLastError();
			if(NULL == m_hFileMapObj)
				break;

			//将其映射到本进程的地址空间中
			m_pMapView	= (char *)MapViewOfFile(m_hFileMapObj, FILE_MAP_ALL_ACCESS, 0, 0, 0); 
			if(NULL == m_pMapView)
				break;

			m_pWRPos = reinterpret_cast<PSWRPos>(m_pMapView);
			m_pWRPos->mem_len   = unSMMSize - sizeof(SWRPos);
			m_pWRPos->read_pos  = 0;
			m_pWRPos->write_pos = 0;
			m_pUserBufBasePos = m_pMapView + sizeof(SWRPos);

			m_bSMSuccess = bResult = true;
		} while (false);

		if(!bResult)
		{
			close();
		}

		return bResult;
	}
开发者ID:zhonghao1986cd,项目名称:projects,代码行数:67,代码来源:ShareMemory.cpp

示例8: gimp_plug_in_shm_new

GimpPlugInShm *
gimp_plug_in_shm_new (void)
{
  /* allocate a piece of shared memory for use in transporting tiles
   *  to plug-ins. if we can't allocate a piece of shared memory then
   *  we'll fall back on sending the data over the pipe.
   */

  GimpPlugInShm *shm = g_slice_new0 (GimpPlugInShm);

  shm->shm_ID = -1;

#if defined(USE_SYSV_SHM)

  /* Use SysV shared memory mechanisms for transferring tile data. */
  {
    shm->shm_ID = shmget (IPC_PRIVATE, TILE_MAP_SIZE, IPC_CREAT | 0600);

    if (shm->shm_ID != -1)
      {
        shm->shm_addr = (guchar *) shmat (shm->shm_ID, NULL, 0);

        if (shm->shm_addr == (guchar *) -1)
          {
            g_printerr ("shmat() failed: %s\n" ERRMSG_SHM_DISABLE,
                        g_strerror (errno));
            shmctl (shm->shm_ID, IPC_RMID, NULL);
            shm->shm_ID = -1;
          }

#ifdef IPC_RMID_DEFERRED_RELEASE
        if (shm->shm_addr != (guchar *) -1)
          shmctl (shm->shm_ID, IPC_RMID, NULL);
#endif
      }
    else
      {
        g_printerr ("shmget() failed: %s\n" ERRMSG_SHM_DISABLE,
                    g_strerror (errno));
      }
  }

#elif defined(USE_WIN32_SHM)

  /* Use Win32 shared memory mechanisms for transferring tile data. */
  {
    gint  pid;
    gchar fileMapName[MAX_PATH];

    /* Our shared memory id will be our process ID */
    pid = GetCurrentProcessId ();

    /* From the id, derive the file map name */
    g_snprintf (fileMapName, sizeof (fileMapName), "GIMP%d.SHM", pid);

    /* Create the file mapping into paging space */
    shm->shm_handle = CreateFileMapping (INVALID_HANDLE_VALUE, NULL,
                                         PAGE_READWRITE, 0,
                                         TILE_MAP_SIZE,
                                         fileMapName);

    if (shm->shm_handle)
      {
        /* Map the shared memory into our address space for use */
        shm->shm_addr = (guchar *) MapViewOfFile (shm->shm_handle,
                                                  FILE_MAP_ALL_ACCESS,
                                                  0, 0, TILE_MAP_SIZE);

        /* Verify that we mapped our view */
        if (shm->shm_addr)
          {
            shm->shm_ID = pid;
          }
        else
          {
            g_printerr ("MapViewOfFile error: %d... " ERRMSG_SHM_DISABLE,
                        GetLastError ());
          }
      }
    else
      {
        g_printerr ("CreateFileMapping error: %d... " ERRMSG_SHM_DISABLE,
                    GetLastError ());
      }
  }

#elif defined(USE_POSIX_SHM)

  /* Use POSIX shared memory mechanisms for transferring tile data. */
  {
    gint  pid;
    gchar shm_handle[32];
    gint  shm_fd;

    /* Our shared memory id will be our process ID */
    pid = gimp_get_pid ();

    /* From the id, derive the file map name */
    g_snprintf (shm_handle, sizeof (shm_handle), "/gimp-shm-%d", pid);

//.........这里部分代码省略.........
开发者ID:STRNG,项目名称:gimp,代码行数:101,代码来源:gimppluginshm.c

示例9: g_mapped_file_new


//.........这里部分代码省略.........
      gchar *display_filename = g_filename_display_name (filename);
      
      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (save_errno),
                   _("Failed to open file '%s': open() failed: %s"),
                   display_filename, 
		   g_strerror (save_errno));
      g_free (display_filename);
      return NULL;
    }

  file = g_slice_new0 (GMappedFile);
  file->ref_count = 1;
  file->free_func = g_mapped_file_destroy;

  if (fstat (fd, &st) == -1)
    {
      int save_errno = errno;
      gchar *display_filename = g_filename_display_name (filename);

      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (save_errno),
                   _("Failed to get attributes of file '%s': fstat() failed: %s"),
                   display_filename, 
		   g_strerror (save_errno));
      g_free (display_filename);
      goto out;
    }

  if (st.st_size == 0)
    {
      file->length = 0;
      file->contents = NULL;
      close (fd);
      return file;
    }

  file->contents = MAP_FAILED;

#ifdef HAVE_MMAP
  if (st.st_size > G_MAXSIZE)
    {
      errno = EINVAL;
    }
  else
    {      
      file->length = (gsize) st.st_size;
      file->contents = (gchar *) mmap (NULL,  file->length,
				       writable ? PROT_READ|PROT_WRITE : PROT_READ,
				       MAP_PRIVATE, fd, 0);
    }
#endif
#ifdef G_OS_WIN32
  file->length = st.st_size;
  file->mapping = CreateFileMapping ((HANDLE) _get_osfhandle (fd), NULL,
				     writable ? PAGE_WRITECOPY : PAGE_READONLY,
				     0, 0,
				     NULL);
  if (file->mapping != NULL)
    {
      file->contents = MapViewOfFile (file->mapping,
				      writable ? FILE_MAP_COPY : FILE_MAP_READ,
				      0, 0,
				      0);
      if (file->contents == NULL)
	{
	  file->contents = MAP_FAILED;
	  CloseHandle (file->mapping);
	  file->mapping = NULL;
	}
    }
#endif

  
  if (file->contents == MAP_FAILED)
    {
      int save_errno = errno;
      gchar *display_filename = g_filename_display_name (filename);
      
      g_set_error (error,
		   G_FILE_ERROR,
		   g_file_error_from_errno (save_errno),
		   _("Failed to map file '%s': mmap() failed: %s"),
		   display_filename,
		   g_strerror (save_errno));
      g_free (display_filename);
      goto out;
    }

  close (fd);
  return file;

 out:
  close (fd);
  g_slice_free (GMappedFile, file);

  return NULL;
}
开发者ID:MacIrssi,项目名称:MILibs,代码行数:101,代码来源:gmappedfile.c

示例10: MapFile

/***    MapFile - Map existing file to memory address
 *
 *  Entry:
 *      pmmf   - Pointer to structure to receive mapping information
 *      psz    - File name
 *      fWrite - TRUE => read/write access, else read-only access
 *
 *  Exit-Success:
 *      Returns TRUE; pmmf filled in
 *
 *  Exit-Failure:
 *      Returns FALSE.
 */
BOOL MapFile(PMEMORYMAPPEDFILE pmmf, char *psz, BOOL fWrite)
{
    ULONG       ul;
    DWORD       fdwAccess;
    DWORD       fdwShareMode;
    DWORD       fdwProtect;
    DWORD       fdwAccessMapping;

    // Construct access settings
    if (fWrite) {
        fdwAccess = GENERIC_READ | GENERIC_WRITE;
        fdwShareMode = 0;               // Do not permit any other access
        fdwProtect = PAGE_READWRITE;
        fdwAccessMapping = FILE_MAP_WRITE;
        }
    else {
        fdwAccess = GENERIC_READ;
        fdwShareMode = FILE_SHARE_READ; // Allow other readers
        fdwProtect = PAGE_READONLY;
        fdwAccessMapping = FILE_MAP_READ;
    }

    //** Clear structure, to simplify error path
    pmmf->pb     = NULL;
    pmmf->cb     = 0;
    pmmf->hfm    = NULL;
    pmmf->hf     = NULL;
    pmmf->ach[0] = '\0';

    //** Open file
    pmmf->hf = CreateFile(psz,          // file name
                          fdwAccess,    // r/w or read-only
                          fdwShareMode, // allow nothing or allow reading
                          NULL,         // default security
                          OPEN_EXISTING,// file must exist
                          0,            // file attributes are don't care
                          NULL);        // no template file

    if (!pmmf->hf) {
        ul = GetLastError();            // Get last error
        Error("Cannot open file: %s", StringFromWin32ErrorCode(ul));
        goto error;
    }

    //** Get file size
    pmmf->cb = GetFileSize(pmmf->hf, NULL) ;
    if (pmmf->cb == 0xFFFFFFFF) {
        ul = GetLastError();            //** Get error code
        Error("Cannot get file size: %s",StringFromWin32ErrorCode(ul));
        goto error;
    }

    //** Create anonymous, read-only file mapping
    pmmf->hfm = CreateFileMapping(pmmf->hf,NULL,fdwProtect, 0,0, NULL);
    if (!pmmf->hfm) {
        ul = GetLastError();            //** Get error code
        Error("Cannot create file mapping: %s",StringFromWin32ErrorCode(ul));
        goto error;
    }

    //** Map from beginning of file (0,0) for entire length of file (0)
    pmmf->pb = MapViewOfFile(pmmf->hfm,fdwAccessMapping, 0,0, 0);
    if (!pmmf->pb) {
        ul = GetLastError();            //** Get error code
        Error("Cannot map view of file: %s",StringFromWin32ErrorCode(ul));
        goto error;
    }

    //** Save name in mmf structure
    strcpy(pmmf->ach,psz);

    //** Success
    return TRUE;

error:
    //** Clean up mmf

    if (pmmf->hfm) {
        CloseHandle(pmmf->hfm);
        pmmf->hfm = NULL;
    }

    if (pmmf->hf) {
        CloseHandle(pmmf->hf);
        pmmf->hf = NULL;
    }

//.........这里部分代码省略.........
开发者ID:rickerliang,项目名称:OpenNT,代码行数:101,代码来源:filetype.c

示例11: Entry


//.........这里部分代码省略.........
              delayed_writeback = true;
              break;
            case 2: // DRIVE_REMOVABLE
              DEBUG ("Drive for file \"" + Entry::name + "\" detected as removable; using memory-mapping");
              break;
            case 3: // DRIVE_FIXED
              DEBUG ("Drive for file \"" + Entry::name + "\" detected as fixed; using memory-mapping");
              break;
            case 4: // DRIVE_REMOTE
              DEBUG ("Drive for file \"" + Entry::name + "\" detected as network - using delayed write-back");
              delayed_writeback = true;
              break;
            case 5: // DRIVE_CDROM
              DEBUG ("Drive for file \"" + Entry::name + "\" detected as CD-ROM - using delayed write-back");
              delayed_writeback = true;
              break;
            case 6: // DRIVE_RAMDISK
              DEBUG ("Drive for file \"" + Entry::name + "\" detected as RAM - using memory-mapping");
              break;
          }

        } else {
          DEBUG ("unable to query root drive path for file \"" + Entry::name + "\"; using delayed write-back");
          delayed_writeback = true;
        }
#else
        struct statfs fsbuf;
        if (statfs (Entry::name.c_str(), &fsbuf)) {
          DEBUG ("cannot get filesystem information on file \"" + Entry::name + "\": " + strerror (errno));
          DEBUG ("  defaulting to delayed write-back");
          delayed_writeback = true;
        }

        if (fsbuf.f_type == 0xff534d42 /* CIFS */|| fsbuf.f_type == 0x6969 /* NFS */ || 
            fsbuf.f_type == 0x65735546 /* FUSE */ || fsbuf.f_type == 0x517b /* SMB */
#ifdef MRTRIX_MACOSX
            || fsbuf.f_type == 0x0017 /* OSXFUSE */
#endif 
        ) {
          DEBUG ("\"" + Entry::name + "\" appears to reside on a networked filesystem - using delayed write-back");
          delayed_writeback = true;
        }
#endif

        if (delayed_writeback) {
          try {
            first = new uint8_t [msize];
            if (!first) throw 1;
          }
          catch (...) {
            throw Exception ("error allocating memory to hold mmap buffer contents");
          }

          if (preload) {
            CONSOLE ("preloading contents of mapped file \"" + Entry::name + "\"...");
            std::ifstream in (Entry::name.c_str(), std::ios::in | std::ios::binary);
            if (!in) 
              throw Exception ("failed to open file \"" + Entry::name + "\": " + strerror (errno));
            in.seekg (start, in.beg);
            in.read ((char*) first, msize);
            if (!in.good())
              throw Exception ("error preloading contents of file \"" + Entry::name + "\": " + strerror(errno));
          }
          else 
            memset (first, 0, msize);
          DEBUG ("file \"" + Entry::name + "\" held in RAM at " + str ( (void*) first) + ", size " + str (msize));

          return;
        }
      }

      // use regular memory-mapping:

      if ( (fd = open (Entry::name.c_str(), ( readwrite ? O_RDWR : O_RDONLY ), 0666)) < 0)
        throw Exception ("error opening file \"" + Entry::name + "\": " + strerror (errno));

      try {
#ifdef MRTRIX_WINDOWS
        HANDLE handle = CreateFileMapping ( (HANDLE) _get_osfhandle (fd), NULL,
            ( readwrite ? PAGE_READWRITE : PAGE_READONLY ), 0, start + msize, NULL);
        if (!handle) throw 0;
        addr = static_cast<uint8_t*> (MapViewOfFile (handle, ( readwrite ? FILE_MAP_ALL_ACCESS : FILE_MAP_READ ), 0, 0, start + msize));
        if (!addr) throw 0;
        CloseHandle (handle);
#else
        addr = static_cast<uint8_t*> (mmap ( (char*) 0, start + msize,
              ( readwrite ? PROT_WRITE | PROT_READ : PROT_READ ), MAP_SHARED, fd, 0));
        if (addr == MAP_FAILED) throw 0;
#endif
      }
      catch (...) {
        close (fd);
        addr = NULL;
        throw Exception ("memory-mapping failed for file \"" + Entry::name + "\": " + strerror (errno));
      }
      first = addr + start;

      DEBUG ("file \"" + Entry::name + "\" mapped at " + str ( (void*) addr) + ", size " + str (msize)
          + " (read-" + (readwrite ? "write" : "only") + ")");
    }
开发者ID:yzhizai,项目名称:mrtrix3,代码行数:101,代码来源:mmap.cpp

示例12: main

int __cdecl main(int argc, char *argv[])
{
    HANDLE  FileMappingHandle;
    HANDLE  OpenFileMappingHandle;
    HANDLE  lpMapViewAddress;
    HANDLE  OpenFileMappingHandle2;
    HANDLE  lpMapViewAddress2;
    const   int LOWORDERSIZE = 1024;
    char    MapObject[] = "myMappingObject";
    char    buf[] = "this is a test";
    char    ch[1024];
    int     RetVal = PASS;


    /* Initialize the PAL environment.
     */
    if(0 != PAL_Initialize(argc, argv))
    {
        return FAIL;
    }

    /* Create a named file-mapping object with file handle FileHandle.
     */
    FileMappingHandle = CreateFileMapping(
                                INVALID_HANDLE_VALUE,
                                NULL,               /* not inherited */
                                PAGE_READWRITE,     /* read and write */
                                0,                  /* high-order size */
                                LOWORDERSIZE,       /* low-order size */
                                MapObject);         /* named object */


    if(NULL == FileMappingHandle) 
    {
        Fail("\nFailed to call CreateFileMapping to create "
             "a mapping object!\n");
    }
    if(GetLastError() == ERROR_ALREADY_EXISTS)
    {
        Trace("\nFile mapping object already exists!\n");
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Open a named file-mapping object with FILE_MAP_WRITE access.
     */
    OpenFileMappingHandle =  OpenFileMapping(
                                    FILE_MAP_WRITE,
                                    FALSE,
                                    MapObject);

    if(NULL == OpenFileMappingHandle)
    {
        Trace("\nFailed to Call OpenFileMapping API!\n");
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Open a named file-mapping object with 
     * FILE_MAP_ALL_ACCESS access, to verify
     * the FILE_MAP_WRITE access map.
     */
    OpenFileMappingHandle2 =  OpenFileMapping(
                                    FILE_MAP_ALL_ACCESS,
                                    FALSE,
                                    MapObject);

    if(NULL == OpenFileMappingHandle2)
    {
        Trace("\nFailed to Call OpenFileMapping API!\n");
        RetVal = FAIL;
        goto CleanUpTwo;
    }

    /* Create map view of the open mapping that has
     * FILE_MAP_WRITE access.
     */
    lpMapViewAddress = MapViewOfFile(
                            OpenFileMappingHandle,
                            FILE_MAP_WRITE,      /* access code */
                            0,                   /* high order offset */
                            0,                   /* low order offset */
                            LOWORDERSIZE);       /* number of bytes for map */

    if(NULL == lpMapViewAddress)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpThree;
    }

    /* Create map view of the open mapping that has
     * FILE_MAP_ALL_ACCESS access.
     */
    lpMapViewAddress2 = MapViewOfFile(
                            OpenFileMappingHandle2,
                            FILE_MAP_ALL_ACCESS, /* access code */
                            0,                   /* high order offset */
//.........这里部分代码省略.........
开发者ID:Afshintm,项目名称:coreclr,代码行数:101,代码来源:OpenFileMappingA.c

示例13: Apply_patches

void  Apply_patches(HWND hwnd)
{
	HWND hList = GetDlgItem(hwnd,IDC_LIST_SEGMEN);
	netnode n("$ Apply SegMen");
	char szFilePath[256 * 2] = {0};
	strncpy(szFilePath, database_idb, 256);
	char *lpTmpBuf = strrchr(szFilePath, '\\') + 1;
	if(lpTmpBuf == (char*)1)
	{
		return;
	}
	*lpTmpBuf = 0;
	get_root_filename(lpTmpBuf, 256);
	msg("=============================\n");
	msg("Apply Path:%s\n", szFilePath);
	if(IsDlgButtonChecked(hwnd, IDC_APPLY_CHECK_BACK))
	{
		char szBackPath[300] = {0};
		sprintf(szBackPath, "%s.back", szFilePath);
		msg("BackFile Path:%s.back\n", szFilePath);
		CopyFile(szFilePath, szBackPath, FALSE);
		n.altset(CHECK_BACKFILE_INDEX, 1);
	}
	else
	{
		n.altset(CHECK_BACKFILE_INDEX, 0);
	}
	HANDLE hFile=CreateFile(szFilePath, GENERIC_WRITE | GENERIC_READ, 0, 
		NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);   //获得文件句柄
	HANDLE hMapping=CreateFileMapping(hFile,NULL,PAGE_READWRITE,0,0,NULL);  //创建内存映射对象
	if(INVALID_HANDLE_VALUE == hMapping)
	{
		msg("CreateFileMapping :%08X ErrorCode:%d\n", hMapping, GetLastError());
		return ;
	}
	unsigned char* pvFile=(unsigned char*)MapViewOfFile(hMapping,FILE_MAP_ALL_ACCESS,0,0,0); //创建视图 就是映射文件到内存;

	int i;
	segment_t *curseg;
	int seg_qty = get_segm_qty();
	for(i=0 ; i < seg_qty; i++)
	{
		char segname[0x100] = {0};
		curseg = getnseg(i);
		get_true_segm_name(curseg, segname, 255);
		int offset = get_fileregion_offset(curseg->startEA);
		int nSize = curseg->endEA - curseg->startEA;
		int nSelectStat = CheckedListBox_GetCheckState(hList, i);
		n.altset(i, nSelectStat);
		if(offset > 0 && nSelectStat)
		{
			//msg("offset:%X  segname:%s EA:%08X, nSize: %X\n", offset, segname, curseg->startEA, nSize);
			unsigned char *lpMem = (unsigned char*)malloc(nSize + 1);
			memset(lpMem, 0, nSize + 1);
			//if(get_many_bytes(curseg->startEA, lpMem, nSize))
			if(segReadBuf(curseg->startEA, lpMem, nSize))
			{
				msg("Apply SegMenName: %s\n", segname);
				SegWriteFile(pvFile, lpMem, nSize, offset);
			}
			//msg("lpMem:%X\n", lpMem);
			free(lpMem);
		}

		//	msg("Name:%s, StartEA:%08X, Offset:%08X, EndEA:%08X\n", segname, curseg->startEA, offset, curseg->endEA);


	}
	CloseHandle(hMapping);
	//	msg("CloseHandle(hMapping)\n");
	if(0 == UnmapViewOfFile(pvFile) )
	{
		msg("文件同步失败! ErrorCode:%d\n", GetLastError());
	}
	else
	{
		msg("文件同步成功!\n");
		msg("=============================\n");
	}
	//	msg("UnmapViewOfFile(pvFile);\n");
	CloseHandle(hFile);
	
	return;
}
开发者ID:boogie1337,项目名称:IDAplugins,代码行数:84,代码来源:ApplyDlg.cpp

示例14: DumpFile

/*
 *----------------------------------------------------------------------
 * DumpFile --
 *
 *	Open up a file, memory map it, and call the appropriate
 *	dumping routine
 *----------------------------------------------------------------------
 */
void
DumpFile(LPSTR filename, FILE *fout, int full)
{
	HANDLE hFile;
	HANDLE hFileMapping;
	LPVOID lpFileBase;
	PIMAGE_DOS_HEADER dosHeader;

	hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
					   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

	if (hFile == INVALID_HANDLE_VALUE) {
		fprintf(stderr, "Couldn't open file with CreateFile(%s)\n", filename);
		return;
	}

	hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
	if (hFileMapping == 0) {
		CloseHandle(hFile);
		fprintf(stderr, "Couldn't open file mapping with CreateFileMapping()\n");
		return;
	}

	lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
	if (lpFileBase == 0) {
		CloseHandle(hFileMapping);
		CloseHandle(hFile);
		fprintf(stderr, "Couldn't map view of file with MapViewOfFile()\n");
		return;
	}

	dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
	if (dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
#if 0
		DumpExeFile( dosHeader );
#else
		fprintf(stderr, "File is an executable.  I don't dump those.\n");
		return;
#endif
	}
	/* Does it look like a i386 COFF OBJ file??? */
	else if ((dosHeader->e_magic == e_magic_number)
			&& (dosHeader->e_sp == 0)) {
		/*
		 * The two tests above aren't what they look like.  They're
		 * really checking for IMAGE_FILE_HEADER.Machine == i386 (0x14C)
		 * and IMAGE_FILE_HEADER.SizeOfOptionalHeader == 0;
		 */
		DumpObjFile((PIMAGE_FILE_HEADER) lpFileBase, fout, full);
	} else if (*((BYTE *)lpFileBase) == 0x80) {
		/*
		 * This file looks like it might be a ROMF file.
		 */
		DumpROMFObjFile(lpFileBase, fout);
	} else {
		printf("unrecognized file format\n");
	}
	UnmapViewOfFile(lpFileBase);
	CloseHandle(hFileMapping);
	CloseHandle(hFile);
}
开发者ID:embedthis,项目名称:appweb-2,代码行数:69,代码来源:dumpext.c

示例15: p11_mmap_open

p11_mmap *
p11_mmap_open (const char *path,
               struct stat *sb,
               void **data,
               size_t *size)
{
	HANDLE mapping;
	LARGE_INTEGER large;
	DWORD errn;
	p11_mmap *map;

	map = calloc (1, sizeof (p11_mmap));
	if (map == NULL) {
		errno = ENOMEM;
		return NULL;
	}

	map->file  = CreateFile (path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
	if (map->file == INVALID_HANDLE_VALUE) {
		errn = GetLastError ();
		free (map);
		SetLastError (errn);
		if (errn == ERROR_PATH_NOT_FOUND || errn == ERROR_FILE_NOT_FOUND)
			errno = ENOENT;
		else if (errn == ERROR_ACCESS_DENIED)
			errno = EPERM;
		return NULL;
	}

	if (sb == NULL) {
		if (!GetFileSizeEx (map->file, &large)) {
			errn = GetLastError ();
			CloseHandle (map->file);
			free (map);
			SetLastError (errn);
			if (errn == ERROR_ACCESS_DENIED)
				errno = EPERM;
			return NULL;
		}
	} else {
		large.QuadPart = sb->st_size;
	}

	mapping = CreateFileMapping (map->file, NULL, PAGE_READONLY, 0, 0, NULL);
	if (!mapping) {
		errn = GetLastError ();
		CloseHandle (map->file);
		free (map);
		SetLastError (errn);
		if (errn == ERROR_ACCESS_DENIED)
			errno = EPERM;
		return NULL;
	}

	map->data = MapViewOfFile (mapping, FILE_MAP_READ, 0, 0, large.QuadPart);
	CloseHandle (mapping);

	if (map->data == NULL) {
		errn = GetLastError ();
		CloseHandle (map->file);
		free (map);
		SetLastError (errn);
		if (errn == ERROR_ACCESS_DENIED)
			errno = EPERM;
		return NULL;
	}

	*data = map->data;
	*size = large.QuadPart;
	return map;
}
开发者ID:lkundrak,项目名称:p11-kit,代码行数:71,代码来源:compat.c


注:本文中的MapViewOfFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。