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


C++ CreateFileMapping函数代码示例

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


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

示例1: open_map_context

/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
pmap_context open_map_context(_In_ const wchar_t* file_path)
{
	_ASSERTE(NULL != file_path);
	if (NULL == file_path) return false;
	if (!is_file_existsW(file_path)) return false;;

	pmap_context ctx = (pmap_context)malloc(sizeof(map_context));
	RtlZeroMemory(ctx, sizeof(map_context));

	bool ret = false;

#pragma warning(disable: 4127)
	do
	{
		ctx->handle = CreateFileW(
			(LPCWSTR)file_path,
			GENERIC_READ,
			NULL,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == ctx->handle)
		{
			print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		// check file size
		//
		LARGE_INTEGER fileSize;
		if (TRUE != GetFileSizeEx(ctx->handle, &fileSize))
		{
			print("err ] GetFileSizeEx( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		// [ WARN ]
		//
		// 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나
		// 파일 포인터 이동이 문제가 됨
		// FilIoHelperClass 모듈을 이용해야 함
		//
		_ASSERTE(fileSize.HighPart == 0);
		if (fileSize.HighPart > 0)
		{
			print("err ] file is too large to map. file = %ws, size = %llu", file_path, fileSize.QuadPart);
			break;
		}

		ctx->size = (DWORD)fileSize.QuadPart;
		ctx->map = CreateFileMapping(
			ctx->handle,
			NULL,
			PAGE_READONLY,
			0,
			0,
			NULL
			);
		if (NULL == ctx->map)
		{
			print("err ] CreateFileMapping( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ctx->view = (PCHAR)MapViewOfFile(
			ctx->map,
			FILE_MAP_READ,
			0,
			0,
			0
			);
		if (ctx->view == NULL)
		{
			print("err ] MapViewOfFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ret = true;
	} while (FALSE);
#pragma warning(default: 4127)

	if (!ret)
	{
		if (NULL != ctx->view) UnmapViewOfFile(ctx->view);
		if (NULL != ctx->map) CloseHandle(ctx->map);
		if (INVALID_HANDLE_VALUE != ctx->handle) CloseHandle(ctx->handle);

		free(ctx); ctx = NULL;
	}
//.........这里部分代码省略.........
开发者ID:j31d0,项目名称:OS_HW2,代码行数:101,代码来源:mmio.cpp

示例2: create_map_context

/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
pmap_context create_map_context(_In_ const wchar_t* file_path, _In_ uint32_t file_size)
{
	_ASSERTE(NULL != file_path);
	if (NULL == file_path) return false;
	if (is_file_existsW(file_path))
	{
		DeleteFileW(file_path);
	}

	pmap_context ctx = (pmap_context)malloc(sizeof(map_context));
	RtlZeroMemory(ctx, sizeof(map_context));

	bool ret = false;

#pragma warning(disable: 4127)
	do
	{
		ctx->handle = CreateFileW(
			(LPCWSTR)file_path,
			GENERIC_READ | GENERIC_WRITE,
			NULL,
			NULL,
			CREATE_NEW,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == ctx->handle)
		{
			print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ctx->size = file_size;
		ctx->map = CreateFileMapping(
			ctx->handle,
			NULL,
			PAGE_READWRITE,
			0,
			ctx->size,
			NULL
			);
		if (NULL == ctx->map)
		{
			print("err ] CreateFileMapping( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ctx->view = (PCHAR)MapViewOfFile(
			ctx->map,
			FILE_MAP_WRITE,
			0,
			0,
			ctx->size
			);
		if (ctx->view == NULL)
		{
			print("err ] MapViewOfFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ret = true;
	} while (FALSE);
#pragma warning(default: 4127)

	if (!ret)
	{
		if (NULL != ctx->view) UnmapViewOfFile(ctx->view);
		if (NULL != ctx->map) CloseHandle(ctx->map);
		if (INVALID_HANDLE_VALUE != ctx->handle) CloseHandle(ctx->handle);

		free(ctx); ctx = NULL;
	}

	return ctx;
}
开发者ID:j31d0,项目名称:OS_HW2,代码行数:84,代码来源:mmio.cpp

示例3: main

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

    HANDLE  hFile;
    char    buf[] = "this is a test string";
    char    ch[2048];
    WCHAR   lpFileName[] = {'t','e','s','t','.','t','m','p','\0'};
    HANDLE  hFileMapping;
    LPVOID  lpMapViewAddress;
    int     RetVal = PASS;
    int     err;
    DWORD   dwBytesWritten;


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

    /* Create a file handle with CreateFile.
     */
    hFile = CreateFile( lpFileName,
                        GENERIC_WRITE|GENERIC_READ,
                        FILE_SHARE_READ|FILE_SHARE_WRITE,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR: %u :unable to create file \"%s\".\n",
             GetLastError(),
             lpFileName);
    }

    /* Write to the File handle.
     */ 
    err = WriteFile(hFile,
                    buf,
                    strlen(buf),
                    &dwBytesWritten,
                    NULL);

    if (err == FALSE)
    {
        Trace("ERROR: %u :unable to write to file handle "
                "hFile=0x%lx\n",
                GetLastError(),
                hFile);
        RetVal = FAIL;
        goto CleanUpOne;
    }
    
    /* Flush to the hard-drive.
      */
    FlushFileBuffers(hFile);

    /* Initialize the buffers.
     */
    memset(ch,  0, MAPPINGSIZE);

    /* Create a unnamed file-mapping object with file handle FileHandle
     * and with PAGE_WRITECOPY protection.
     */
    hFileMapping = CreateFileMapping(
                            hFile,
                            NULL,               /*not inherited*/
                            PAGE_WRITECOPY,     /*write copy*/
                            0,                  /*high-order size*/
                            0,                  /*low-order size*/
                            NULL);              /*unnamed object*/

    if(NULL == hFileMapping)
    {
        Trace("ERROR:%u: Failed to create File Mapping.\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* maps a view of a file into the address space of the calling process.
     */
    lpMapViewAddress = MapViewOfFile(
                            hFileMapping,
                            FILE_MAP_COPY,       /* access code */
                            0,                   /* high order offset*/
                            0,                   /* low order offset*/
                            0);                  /* 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 CleanUpTwo;
    }
//.........这里部分代码省略.........
开发者ID:smartmaster,项目名称:sscli,代码行数:101,代码来源:createfilemappingw.c

示例4: read_file_using_memory_map

/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool read_file_using_memory_map()
{
	// current directory 를 구한다.
	wchar_t *buf = NULL;
	uint32_t buflen = 0;
	buflen = GetCurrentDirectoryW(buflen, buf);
	if (0 == buflen)
	{
		print("err ] GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError());
		return false;
	}

	buf = (PWSTR)malloc(sizeof(WCHAR)* buflen);
	if (0 == GetCurrentDirectoryW(buflen, buf))
	{
		print("err ] GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError());
		free(buf);
		return false;
	}

	// current dir \\ test.txt 파일명 생성
	wchar_t file_name[260];
	if (!SUCCEEDED(StringCbPrintfW(
		file_name,
		sizeof(file_name),
		L"%ws\\test.txt",
		buf)))
	{
		print("err ] can not create file name");
		free(buf);
		return false;
	}
	free(buf); buf = NULL;

	if (true != is_file_existsW(file_name))
	{
		print("err ] no file exists. file = %ws", file_name);
		return false;
	}

	HANDLE file_handle = CreateFileW(
		(LPCWSTR)file_name,
		GENERIC_READ,
		NULL,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);
	if (INVALID_HANDLE_VALUE == file_handle)
	{
		print("err ] CreateFile(%ws) failed, gle = %u", file_name, GetLastError());
		return false;
	}

	// check file size
	//
	LARGE_INTEGER fileSize;
	if (TRUE != GetFileSizeEx(file_handle, &fileSize))
	{
		print("err ] GetFileSizeEx(%ws) failed, gle = %u", file_name, GetLastError());
		CloseHandle(file_handle);
		return false;
	}

	// [ WARN ]
	//
	// 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나
	// 파일 포인터 이동이 문제가 됨
	// FilIoHelperClass 모듈을 이용해야 함
	//
	_ASSERTE(fileSize.HighPart == 0);
	if (fileSize.HighPart > 0)
	{
		print("file size = %I64d (over 4GB) can not handle. use FileIoHelperClass",
			fileSize.QuadPart);
		CloseHandle(file_handle);
		return false;
	}

	DWORD file_size = (DWORD)fileSize.QuadPart;
	HANDLE file_map = CreateFileMapping(
		file_handle,
		NULL,
		PAGE_READONLY,
		0,
		0,
		NULL
		);
	if (NULL == file_map)
	{
//.........这里部分代码省略.........
开发者ID:j31d0,项目名称:OS_HW2,代码行数:101,代码来源:mmio.cpp

示例5: CreateFile

char *get_file_contents (const char *filename) {
#ifdef USE_MEMORY_MAPPED_FILES
	HANDLE hFile = CreateFile(
		filename,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		return NULL;
	}

	HANDLE hMapFile = CreateFileMapping(
		hFile,
		NULL,
		PAGE_READONLY,
		0L,
		0L,
		NULL);

	LPBYTE lpData = (LPBYTE) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
	return (char *) lpData;
#else
	FILE *file;
	char *buffer, *p;
	size_t size, read_size;

	// first try to open it
	file = fopen (filename, "rb");

	if (!file)
		return NULL;

	// find file size (Spencer says it's not a hack)
	fseek (file, 0, SEEK_END);
	size = ftell (file);
	rewind (file);


	// now allocate the memory and read in the contents
	buffer = (char *) malloc (size + 1);

	const unsigned char utf8_endian_mark[] = {0xEF, 0xBB, 0xBF};
	fread(buffer, 1, sizeof(utf8_endian_mark), file);
	if (memcmp(buffer, &utf8_endian_mark, sizeof(utf8_endian_mark)) == 0) {
		size -= sizeof(utf8_endian_mark);
		p = (char *) malloc (size + 1);
		memcpy(p, buffer + sizeof(utf8_endian_mark), size);
		free(buffer);
	} else {
		p = buffer;
		rewind(file);
	}

	read_size = fread (p, 1, size, file);
	fclose (file);

	if (read_size != size) {
		free (buffer);
		return NULL;
	}

	p[size] = '\0';
	return p;
#endif
}
开发者ID:RickyXwang,项目名称:transf-badapple,代码行数:69,代码来源:utils.cpp

示例6: while

WDL_SHM_Connection::WDL_SHM_Connection(bool whichChan,
                      const char *uniquestring, // identify 
                      int shmsize, // bytes, whoever opens first decides
                      int timeout_sec,
                      int extra_flags // unused on win32

                    )
{
  m_timeout_cnt=0;
  m_timeout_sec=timeout_sec;
  m_last_recvt=time(NULL)+2; // grace period
  { // make shmsize the next power of two
    int a = shmsize;
    shmsize=2;
    while (shmsize < SHM_MINSIZE || shmsize<a) shmsize*=2;
  }

  m_file=INVALID_HANDLE_VALUE;
  m_filemap=NULL;
  m_mem=NULL;
  m_lockmutex=m_events[0]=m_events[1]=NULL;

  m_whichChan=whichChan ? 1 : 0;

  char buf[512];
  GetTempPath(sizeof(buf)-4,buf);
  if (!buf[0]) lstrcpyn(buf,"C:\\",32);
  if (buf[strlen(buf)-1] != '/' && buf[strlen(buf)-1] != '\\') strcat(buf,"\\");
  m_tempfn.Set(buf);
  m_tempfn.Append("WDL_SHM_");
  m_tempfn.Append(uniquestring);
  m_tempfn.Append(".tmp");

  WDL_String tmp;
  if (!(GetVersion()&0x80000000)) tmp.Set("Global\\WDL_SHM_");
  else tmp.Set("WDL_SHM_");
  tmp.Append(uniquestring);
  int tmp_l = strlen(tmp.Get());

  tmp.Append(".m");
  HANDLE mutex = CreateMutex(NULL,FALSE,tmp.Get());

  if (mutex) WaitForSingleObject(mutex,INFINITE);

  tmp.Get()[tmp_l]=0;
  tmp.Append(whichChan?".l1":".l0");
  m_lockmutex = CreateMutex(NULL,FALSE,tmp.Get());
  if (m_lockmutex)
  {
    if (WaitForSingleObject(m_lockmutex,100) == WAIT_OBJECT_0)
    {
      DeleteFile(m_tempfn.Get()); // this is designed to fail if another process has it locked

      m_file=CreateFile(m_tempfn.Get(),GENERIC_READ|GENERIC_WRITE,
                        FILE_SHARE_READ|FILE_SHARE_WRITE ,
                        NULL,whichChan ? OPEN_EXISTING : OPEN_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL);
    }
    else
    {
      CloseHandle(m_lockmutex);
      m_lockmutex=0;
    }
  }
  
  int mapsize;
  if (m_file != INVALID_HANDLE_VALUE && 
        ((mapsize=GetFileSize(m_file,NULL)) < SHM_HDRSIZE+SHM_MINSIZE*2 || 
          mapsize == 0xFFFFFFFF))
  {
    char buf[4096];
    memset(buf,0,sizeof(buf));
    *(int *)buf=shmsize;

    int sz=shmsize*2 + SHM_HDRSIZE;
    while (sz>0)
    {
      DWORD d;
      int a = sz;
      if (a>sizeof(buf))a=sizeof(buf);
      WriteFile(m_file,buf,a,&d,NULL);
      sz-=a;
      *(int *)buf = 0;
    }
  }

  if (m_file!=INVALID_HANDLE_VALUE)
    m_filemap=CreateFileMapping(m_file,NULL,PAGE_READWRITE,0,0,NULL);

  if (m_filemap)
  {
    m_mem=(unsigned char *)MapViewOfFile(m_filemap,FILE_MAP_WRITE,0,0,0);

    tmp.Get()[tmp_l]=0;
    tmp.Append(".1");
    m_events[0]=CreateEvent(NULL,false,false,tmp.Get());
    tmp.Get()[strlen(tmp.Get())-1]++; 
    m_events[1]=CreateEvent(NULL,false,false,tmp.Get());
  }

  if (mutex) 
//.........这里部分代码省略.........
开发者ID:M-l-M,项目名称:wdl,代码行数:101,代码来源:shm_connection.cpp

示例7: XACT3CreateEngine

//=============================================================================
// initialize
// This function does the following:
//      1. Initialize XACT by calling xactEngine->Initialize 
//      2. Create the XACT wave bank(s) you want to use
//      3. Create the XACT sound bank(s) you want to use
//      4. Store indices to the XACT cue(s) your game uses
//=============================================================================
HRESULT Audio::initialize()
{
    HRESULT result = E_FAIL;
    HANDLE hFile;
    DWORD fileSize;
    DWORD bytesRead;
    HANDLE hMapFile;

    if( coInitialized == false)
        return E_FAIL;

    result = XACT3CreateEngine( 0, &xactEngine );
    if( FAILED( result ) || xactEngine == NULL )
        return E_FAIL;

    // Initialize & create the XACT runtime 
    XACT_RUNTIME_PARAMETERS xactParams = {0};
    xactParams.lookAheadTime = XACT_ENGINE_LOOKAHEAD_DEFAULT;
    result = xactEngine->Initialize( &xactParams );
    if( FAILED( result ) )
        return result;

    // Create an "in memory" XACT wave bank file using memory mapped file IO
    result = E_FAIL; // default to failure code, replaced on success
	//create file is not working properly
	auto temp = WAVE_BANK;
    hFile = CreateFileA( WAVE_BANK, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
    if( hFile != INVALID_HANDLE_VALUE )
    {
        fileSize = GetFileSize( hFile, NULL );
        if( fileSize != -1 )
        {
            hMapFile = CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, fileSize, NULL );
            if( hMapFile )
            {
                mapWaveBank = MapViewOfFile( hMapFile, FILE_MAP_READ, 0, 0, 0 );
                if( mapWaveBank )
                    result = xactEngine->CreateInMemoryWaveBank( mapWaveBank, fileSize, 0, 0, &waveBank );

                CloseHandle( hMapFile );    // mapWaveBank maintains a handle on the file so close this unneeded handle
            }
        }
        CloseHandle( hFile );    // mapWaveBank maintains a handle on the file so close this unneeded handle
    }
    if( FAILED( result ) )
        return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );

    // Read and register the sound bank file with XACT.
    result = E_FAIL;    // default to failure code, replaced on success
    hFile = CreateFileA( SOUND_BANK, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
    if( hFile != INVALID_HANDLE_VALUE )
    {
        fileSize = GetFileSize( hFile, NULL );
        if( fileSize != -1 )
        {
            soundBankData = new BYTE[fileSize];    // reserve memory for sound bank
            if( soundBankData )
            {
                if( 0 != ReadFile( hFile, soundBankData, fileSize, &bytesRead, NULL ) )
                    result = xactEngine->CreateSoundBank( soundBankData, fileSize, 0, 0, &soundBank );
            }
        }
        CloseHandle( hFile );
    }
    if( FAILED( result ) )
        return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );

    return S_OK;
}
开发者ID:gearhartjj1,项目名称:SpaceEvaders,代码行数:77,代码来源:audio.cpp

示例8: CreateFile

bool ShareMemory::Create()
{
#ifdef WIN32
	m_hFile = (HANDLE)0xFFFFFFFF;// system
	if ("" != m_mapFilePath)
	{
		string strFile = m_mapFilePath + "/" + m_shareName;
		// file
		m_hFile = CreateFile(
			strFile.c_str(),
			GENERIC_READ|GENERIC_WRITE,
			FILE_SHARE_READ|FILE_SHARE_WRITE,
			NULL,
			OPEN_ALWAYS,//OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if ( INVALID_HANDLE_VALUE == m_hFile ) 
		{
			m_lastError = "open file error:" + strFile;
			return false;
		}
	}
	m_hFileMap = CreateFileMapping( m_hFile, NULL, PAGE_READWRITE, 
									0, m_dwSize, m_shareName.c_str() );
	if (NULL == m_hFileMap) 
	{
		m_lastError = "create file mapping error";
		return false;
	}
#else
	if ( -1 == m_digName ) 
	{
		if ( "" == m_shareName ) 
		{
			m_lastError = "key is null";
			return false;
		}
		m_digName = atoi( m_shareName.c_str() );
		if ( 0 >= m_digName ) 
		{
			m_lastError = "key havo to bigger than 0";
			return false;
		}
	}
	m_shmid = shmget( m_digName, m_dwSize, IPC_CREAT|IPC_EXCL );
	if ( -1 == m_shmid )
	{
		if ( EEXIST == errno ) 
		{
			m_shmid = shmget( m_digName, m_dwSize, 0666 );
		}
		if ( -1 == m_shmid ) 
		{
			m_lastError = "open error:";
			if ( EINVAL == errno )
			{
				m_lastError += "size < SHMMIN or size > SHM-MAX";
				m_lastError += ", or segment is exist, but size is small than the new size";
			}
			if ( EIDRM == errno ) m_lastError += "segment is delete";
			if ( ENOSPC == errno ) m_lastError += "requested size would cause the  system  to exceed the system-wide limit on shared memory (SHMALL)";
			if ( ENOENT == errno ) m_lastError += "No segment exists";
			if ( EACCES == errno ) m_lastError += "not have permission to access";
			if ( ENOMEM == errno ) m_lastError += "No memory could be allocated for segment overhead";
			if ( ENFILE == errno ) m_lastError += "open too many file";
			return false;
		}
	}
#endif
	return true;
}
开发者ID:huhueagle,项目名称:Exist,代码行数:72,代码来源:ShareMemory.cpp

示例9: FcDirCacheMapFd

/*
 * Map a cache file into memory
 */
static FcCache *
FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
{
    FcCache	*cache;
    FcBool	allocated = FcFalse;

    if (fd_stat->st_size < (int) sizeof (FcCache))
	return NULL;
    cache = FcCacheFindByStat (fd_stat);
    if (cache)
    {
	if (FcCacheTimeValid (config, cache, dir_stat) &&
	    FcCacheDirsValid (config, cache))
	    return cache;
	FcDirCacheUnload (cache);
	cache = NULL;
    }

    /*
     * Large cache files are mmap'ed, smaller cache files are read. This
     * balances the system cost of mmap against per-process memory usage.
     */
    if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
    {
#if defined(HAVE_MMAP) || defined(__CYGWIN__)
	cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
#if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
	posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
#endif
	if (cache == MAP_FAILED)
	    cache = NULL;
#elif defined(_WIN32)
	{
	    HANDLE hFileMap;

	    cache = NULL;
	    hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
					 PAGE_READONLY, 0, 0, NULL);
	    if (hFileMap != NULL)
	    {
		cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
				       fd_stat->st_size);
		CloseHandle (hFileMap);
	    }
	}
#endif
    }
    if (!cache)
    {
	cache = malloc (fd_stat->st_size);
	if (!cache)
	    return NULL;

	if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
	{
	    free (cache);
	    return NULL;
	}
	allocated = FcTrue;
    }
    if (cache->magic != FC_CACHE_MAGIC_MMAP ||
	cache->version < FC_CACHE_VERSION_NUMBER ||
	cache->size != (intptr_t) fd_stat->st_size ||
	!FcCacheTimeValid (config, cache, dir_stat) ||
	!FcCacheDirsValid (config, cache) ||
	!FcCacheInsert (cache, fd_stat))
    {
	if (allocated)
	    free (cache);
	else
	{
#if defined(HAVE_MMAP) || defined(__CYGWIN__)
	    munmap (cache, fd_stat->st_size);
#elif defined(_WIN32)
	    UnmapViewOfFile (cache);
#endif
	}
	return NULL;
    }

    /* Mark allocated caches so they're freed rather than unmapped */
    if (allocated)
	cache->magic = FC_CACHE_MAGIC_ALLOC;
	
    return cache;
}
开发者ID:santhoshtr,项目名称:fontconfig,代码行数:89,代码来源:fccache.c

示例10: doHandshake

char doHandshake( bool isD3DCalling, Handshake** handshake )
{
    const unsigned char partState = isD3DCalling ? 1 : 2;
    if ( isD3DCalling )
        logg( "Doing Handshake from D3D side..." );
    else
        logg( "Doing Handshake from Plugin side..." );
    
    HANDLE hmmf = CreateFileMapping( (HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, 1024, MEM_KEY );
    
    if ( hmmf == NULL )
    {
        logg( "ERROR: Handshake failed. Unable to create PAGEFILE Memory Mapped File." );
        return ( -1 );
    }
    
    unsigned char* mem0 = (unsigned char*)MapViewOfFile( hmmf, FILE_MAP_WRITE, 0, 0, 0 );
    unsigned char* mem = mem0;
    
    if ( mem == NULL )
    {
        logg( "ERROR: Handshake failed. Unable to get a pointer to memory of PAGEFILE Memory Mapped File." );
        return ( -1 );
    }
    
    logg( "    Successfully created a pointer to a PAGEFILE Memory Mapped File." );
    
    DWORD procId = GetCurrentProcessId();
    
    unsigned char initializeMem = 0;
    if ( !checkMemKey( (char*)mem ) )
        initializeMem = 1;
    else if ( *(DWORD*)( mem + 8 ) != procId )
        initializeMem = 2;
    
    if ( initializeMem != 0 )
    {
        if ( initializeMem == 1 )
            logg( "    Found virgin memory." );
        else if ( initializeMem == 2 )
            logg( "    Found outdated memory." );
        
        memcpy( mem, MEM_KEY, 8 );
        mem += 8;
        *(DWORD*)mem = procId;
        mem += sizeof( DWORD );
        *mem = partState;
        mem += 1;
        
        *handshake = new Handshake();
        (*handshake)->isPluginEnabled = true;
        (*handshake)->state = HANDSHAKE_STATE_WAITING_FOR_OTHER_SIDE;
        *(unsigned long long*)mem = (unsigned long long)*handshake;
        
        UnmapViewOfFile( mem0 );
        
        logg( "First part of Handshake successful." );
        
        return ( 0 ); // Handshake incomplete
    }
    
    mem += 8 + sizeof( DWORD );
    
    unsigned char state = *mem;
    
    if ( ( state & partState ) != 0 )
    {
        UnmapViewOfFile( mem0 );
        
        logg( "Handshake repeat detected for unknown reason. This tends to happen in windowed mode, where two D3D contexts seem to be created. Skipping!" );
        
        return ( 2 );
    }
    
    *mem = state | partState;
    
    mem += 1;
    
    logg( "    Found first part of handshake. Doing second part..." );
    
    *handshake = (Handshake*)(*(unsigned long long*)mem);
    (*handshake)->state = HANDSHAKE_STATE_COMPLETE;
    
    UnmapViewOfFile( mem0 );
    
    logg( "Second part of Handshake successful. Handshake complete." );
    
    return ( 1 );
}
开发者ID:r-h-o,项目名称:rfDynHUD,代码行数:89,代码来源:handshake.cpp

示例11: warning

/**----------------------------------------------------------------------------
\brief		FileSize 바이트 짜리 파일을 생성한다.

\param
\return
\code

\endcode
-----------------------------------------------------------------------------*/
DTSTATUS
FileIoHelper::FIOCreateFile(
IN std::wstring FilePath,
IN LARGE_INTEGER FileSize
)
{
	if (TRUE == Initialized()) { FIOClose(); }
	if (FileSize.QuadPart == 0) return DTS_INVALID_PARAMETER;

	mReadOnly = FALSE;

#pragma warning(disable: 4127)
	DTSTATUS status = DTS_WINAPI_FAILED;
	do
	{
		mFileSize = FileSize;

		mFileHandle = CreateFileW(
			FilePath.c_str(),
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ,		// write 도중 다른 프로세스에서 읽기가 가능
			NULL,
			CREATE_ALWAYS,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == mFileHandle)
		{
				break;
		}

		// increase file size
		// 
		if (TRUE != SetFilePointerEx(mFileHandle, mFileSize, NULL, FILE_BEGIN))
		{
				break;
		}

		if (TRUE != SetEndOfFile(mFileHandle))
		{
				break;
		}

		mFileMap = CreateFileMapping(
			mFileHandle,
			NULL,
			PAGE_READWRITE,
			0,
			0,
			NULL
			);
		if (NULL == mFileMap)
		{
				break;
		}

		status = DTS_SUCCESS;
	} while (FALSE);
#pragma warning(default: 4127)

	if (TRUE != DT_SUCCEEDED(status))
	{
		if (INVALID_HANDLE_VALUE != mFileHandle)
		{
			CloseHandle(mFileHandle);
			mFileHandle = INVALID_HANDLE_VALUE;
		}
		if (NULL != mFileMap) CloseHandle(mFileMap);
	}

	return status;
}
开发者ID:orangee22,项目名称:BoB4_Assignment,代码行数:81,代码来源:FileIoHelperClass.cpp

示例12: mmap

void* mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
{
    HANDLE fm, h;
    
    void * map = MAP_FAILED;
    
    const DWORD dwFileOffsetLow = (sizeof(off_t) <= sizeof(DWORD)) ? 
                    (DWORD)off : (DWORD)(off & 0xFFFFFFFFL);
    const DWORD dwFileOffsetHigh = (sizeof(off_t) <= sizeof(DWORD)) ?
                    (DWORD)0 : (DWORD)((off >> 32) & 0xFFFFFFFFL);
    const DWORD protect = __map_mmap_prot_page(prot);
    const DWORD desiredAccess = __map_mmap_prot_file(prot);

    errno = 0;
    
    if (len == 0 
        /* Unsupported flag combinations */
        || (flags & MAP_FIXED) != 0
        /* Usupported protection combinations */
        || prot == PROT_EXEC)
    {
        errno = EINVAL;
        return MAP_FAILED;
    }
    
    h = ((flags & MAP_ANONYMOUS) == 0) ? 
                    (HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE;

    if ((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE)
    {
        errno = EBADF;
        return MAP_FAILED;
    }

    const off_t maxSize = off + (off_t)len;
    
    const DWORD dwMaxSizeLow = (sizeof(off_t) <= sizeof(DWORD)) ? 
                    (DWORD)maxSize : (DWORD)(maxSize & 0xFFFFFFFFL);
    const DWORD dwMaxSizeHigh = (sizeof(off_t) <= sizeof(DWORD)) ?
                    (DWORD)0 : (DWORD)((maxSize >> 32) & 0xFFFFFFFFL);
    
    fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL);

    if (fm == NULL)
    {
        errno = __map_mman_error(GetLastError(), EPERM);
        return MAP_FAILED;
    }
  
    map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len);

    CloseHandle(fm);
  
    if (map == NULL)
    {
        errno = __map_mman_error(GetLastError(), EPERM);
        return MAP_FAILED;
    }

    return map;
}
开发者ID:CREATEspace,项目名称:VowelCat,代码行数:61,代码来源:mman.c

示例13: shmget

int shmget(key_t key, int size, int shmflg)
{
    PtrHandleChain dummy;
    HANDLE hFile = (HANDLE)0xFFFFFFFF;
    DWORD flProtect;
    char name[100];
    
    if ((key == IPC_PRIVATE) || ((IPC_CREAT & shmflg) == IPC_CREAT))
    {
	if ((shmflg & O_RDONLY) == O_RDONLY)
	    flProtect = PAGE_READONLY;
	else 
	    flProtect = PAGE_READWRITE;
	
	if (key == IPC_PRIVATE)
	{
	    do {
		key++;
		_itoa(key, name, 10);
		if ((hFile != (HANDLE)0xFFFFFFFF) && (hFile != NULL))
		    CloseHandle(hFile);
		hFile = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, flProtect, 0, size, name);
	    } while (GetLastError() != 0);
	} else {
	    _itoa(key, name, 10);
	    hFile = CreateFileMapping(hFile, NULL, flProtect, 0, size, name);
	}
	
	if (hFile == NULL)
	{
	    errno = GetLastError();
	    return(-1);
	}
    } else {
	if ((shmflg & O_RDONLY) == O_RDONLY)
	    flProtect = FILE_MAP_READ;
	else
	    flProtect = FILE_MAP_WRITE;
	
	_itoa(key, name, 10);
	hFile = OpenFileMapping(flProtect, TRUE, name);
	if (hFile == NULL)
	{
	    errno = GetLastError();
	    return(-1);
	}
    }
    
    if (start == NULL)
    {
	start = (PtrHandleChain) malloc(sizeof(HandleChain));
	if (start == NULL)
	    return(-1);
	dummy = start;
    } else
    {
	dummy = start;
	while(dummy->next != NULL)
	    dummy = dummy->next;
	dummy->next = (PtrHandleChain) malloc(sizeof(HandleChain));
	if (dummy == NULL)
	    return(-1);
	dummy = dummy->next;
	
    }
    dummy->next = NULL;
    dummy->handle = hFile;
    dummy->key = key;
    dummy->address = NULL;
    dummy->size = size;
    
    return((int) key);
}
开发者ID:carsten-clauss,项目名称:MP-MPICH,代码行数:73,代码来源:shm.c

示例14: getShmTime

static struct shmTime *
getShmTime (
	int unit
	)
{
#ifndef SYS_WINNT
	int shmid=shmget (0x4e545030+unit, sizeof (struct shmTime), IPC_CREAT|0777);
	if (shmid==-1) {
		perror ("shmget");
		exit (1);
	}
	else {
		struct shmTime *p=(struct shmTime *)shmat (shmid, 0, 0);
		if ((int)(long)p==-1) {
			perror ("shmat");
			p=0;
		}
		assert (p!=0);
		return p;
	}
#else
	char buf[10];
	LPSECURITY_ATTRIBUTES psec=0;
	snprintf (buf, sizeof(buf), "NTP%d", unit);
	SECURITY_DESCRIPTOR sd;
	SECURITY_ATTRIBUTES sa;
	HANDLE shmid;

	assert (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION));
	assert (SetSecurityDescriptorDacl(&sd,1,0,0));
	sa.nLength=sizeof (SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor=&sd;
	sa.bInheritHandle=0;
	shmid=CreateFileMapping ((HANDLE)0xffffffff, 0, PAGE_READWRITE,
				 psec, sizeof (struct shmTime),buf);
	if (!shmid) {
		shmid=CreateFileMapping ((HANDLE)0xffffffff, 0, PAGE_READWRITE,
					 0, sizeof (struct shmTime),buf);
		cout <<"CreateFileMapping with psec!=0 failed"<<endl;
	}

	if (!shmid) {
		char mbuf[1000];
		FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
			       0, GetLastError (), 0, mbuf, sizeof (mbuf), 0);
		int x=GetLastError ();
		cout <<"CreateFileMapping "<<buf<<":"<<mbuf<<endl;
		exit (1);
	}
	else {
		struct shmTime *p=(struct shmTime *) MapViewOfFile (shmid, 
								    FILE_MAP_WRITE, 0, 0, sizeof (struct shmTime));
		if (p==0) {
			char mbuf[1000];
			FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
				       0, GetLastError (), 0, mbuf, sizeof (mbuf), 0);
			cout <<"MapViewOfFile "<<buf<<":"<<mbuf<<endl;
			exit (1);
		}
		return p;
	}
	return 0;
#endif
}
开发者ID:ajinkya93,项目名称:netbsd-src,代码行数:64,代码来源:sht.c

示例15: GetPEFileBit

/*******************************************************************************
*
*   函 数 名 : GetPEFileBit
*  功能描述 : 取得可执行文件的位数
*  参数列表 : pPEFilePath  --     pe文件路径
*   说      明 : 读pe文件的头进内存,再调用GetBitByPEHeader去判断
*  返回结果 :  返回当前进程位数
*
*******************************************************************************/
ULONG   GetPEFileBit(__in_z CONST PTCHAR pPEFilePath)
{
        ULONG uResult(0) ;
        HANDLE hFile(INVALID_HANDLE_VALUE) ;
        HANDLE hFileMap(NULL) ;
        LPVOID pAddr(NULL) ;

        __try
        {
                if (NULL == pPEFilePath)
                {
                        OutputDebugString(TEXT("GetPEFileBit pPEFilePath can't NULL!\r\n")) ;
                        __leave ;
                }
                
                if(FALSE == PathFileExists(pPEFilePath))
                {
                        OutputDebugString(TEXT("The file does not exist!\r\n")) ;
                        __leave ;
                }

                hFile = CreateFile(pPEFilePath, 
                                             GENERIC_READ,
                                             FILE_SHARE_READ,
                                             NULL,
                                             OPEN_EXISTING,
                                             FILE_ATTRIBUTE_NORMAL,
                                             NULL) ;
                if (INVALID_HANDLE_VALUE == hFile)
                {
                        OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("CreateFile")) ;
                        __leave ;
                }

                hFileMap = CreateFileMapping(hFile,
                                                                     NULL,
                                                                     PAGE_READONLY,
                                                                     0,
                                                                     0,
                                                                     NULL) ;
                if (NULL == hFile)
                {
                        OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("CreateFileMapping")) ;
                        __leave ;
                }

                pAddr = MapViewOfFile(hFileMap,
                                                        FILE_MAP_READ,
                                                        0,
                                                        0,
                                                        0) ;

                if (NULL == pAddr)
                {
                        OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("MapViewOfFile")) ;
                        __leave ;
                }

                uResult = GetBitByPEHeader(pAddr, GetFileSize(hFile, NULL)) ;
        }

        __finally
        {
                if (NULL != pAddr)
                {
                        UnmapViewOfFile(pAddr) ;
                        pAddr = NULL ;
                }

                if (NULL != hFileMap)
                {
                        CloseHandle(hFileMap) ;
                        hFileMap = NULL ;
                }

                if (INVALID_HANDLE_VALUE != hFile)
                {
                        CloseHandle(hFile) ;
                        hFile = INVALID_HANDLE_VALUE ;
                }
        }
        return uResult ;
}
开发者ID:CyDoor,项目名称:InjectCode,代码行数:92,代码来源:EnvironmentInformation.cpp


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