• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ FormatMessage函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: pgsymlink

/*
 *	pgsymlink - uses Win32 junction points
 *
 *	For reference:	http://www.codeproject.com/KB/winsdk/junctionpoints.aspx
 */
int
pgsymlink(const char *oldpath, const char *newpath)
{
	HANDLE		dirhandle;
	DWORD		len;
	char		buffer[MAX_PATH * sizeof(WCHAR) + sizeof(REPARSE_JUNCTION_DATA_BUFFER)];
	char		nativeTarget[MAX_PATH];
	char	   *p = nativeTarget;
	REPARSE_JUNCTION_DATA_BUFFER *reparseBuf = (REPARSE_JUNCTION_DATA_BUFFER *) buffer;

	CreateDirectory(newpath, 0);
	dirhandle = CreateFile(newpath, GENERIC_READ | GENERIC_WRITE,
						   0, 0, OPEN_EXISTING,
			   FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0);

	if (dirhandle == INVALID_HANDLE_VALUE)
		return -1;

	/* make sure we have an unparsed native win32 path */
	if (memcmp("\\??\\", oldpath, 4))
		sprintf(nativeTarget, "\\??\\%s", oldpath);
	else
		strcpy(nativeTarget, oldpath);

	while ((p = strchr(p, '/')) != 0)
		*p++ = '\\';

	len = strlen(nativeTarget) * sizeof(WCHAR);
	reparseBuf->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
	reparseBuf->ReparseDataLength = len + 12;
	reparseBuf->Reserved = 0;
	reparseBuf->SubstituteNameOffset = 0;
	reparseBuf->SubstituteNameLength = len;
	reparseBuf->PrintNameOffset = len + sizeof(WCHAR);
	reparseBuf->PrintNameLength = 0;
	MultiByteToWideChar(CP_ACP, 0, nativeTarget, -1,
						reparseBuf->PathBuffer, MAX_PATH);

	/*
	 * FSCTL_SET_REPARSE_POINT is coded differently depending on SDK version;
	 * we use our own definition
	 */
	if (!DeviceIoControl(dirhandle,
	 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_ANY_ACCESS),
						 reparseBuf,
	reparseBuf->ReparseDataLength + REPARSE_JUNCTION_DATA_BUFFER_HEADER_SIZE,
						 0, 0, &len, 0))
	{
		LPSTR		msg;

		errno = 0;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
					  NULL, GetLastError(),
					  MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
					  (LPSTR) &msg, 0, NULL);
#ifndef FRONTEND
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not set junction for \"%s\": %s",
						nativeTarget, msg)));
#else
		fprintf(stderr, _("could not set junction for \"%s\": %s\n"),
				nativeTarget, msg);
#endif
		LocalFree(msg);

		CloseHandle(dirhandle);
		RemoveDirectory(newpath);
		return -1;
	}

	CloseHandle(dirhandle);

	return 0;
}
开发者ID:50wu,项目名称:gpdb,代码行数:80,代码来源:dirmod.c


示例2: openRestoreDrives

void image::restoreImage() 
{
	openRestoreDrives();

	BYTE* buffer = new BYTE[bufferSize];
	LPDWORD bytesRead = new DWORD();
		
	*bytesRead = bufferSize;
	dCompress* comp; 
	comp= new dCompress();
	BYTE* outbuff;
	int outbuffersize;//  = 10000;
	int returnread = 0;
	int returnwrite = 0;
	char message[200];
	int tValue;

	long readSize = 0;
	long writeSize = 0;

	//DWORD *written = 0;
	while (*bytesRead != 0)
	{
		returnread = ReadFile(hFile[0],buffer,bufferSize,bytesRead,NULL);
		//cout << "return read: " << returnread << endl;
		//FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),0, message,200,NULL);
		//cout << "Message: " << message << endl;

		if (buffer [*bytesRead - 1] == (0xFF))
		{
			if ((buffer [*bytesRead -2] == (0xFE)) && (buffer [*bytesRead-3 ] == 0xFF))
			{
				SetFilePointer(hFile[0],-3,NULL,FILE_CURRENT);
				*bytesRead -= 3;			
			}	
			else
			{
				SetFilePointer(hFile[0],-1,NULL,FILE_CURRENT);
				*bytesRead -= 1;
			}		
		}
			
		if	(buffer [*bytesRead - 2] == (0xFF))
		{
			SetFilePointer(hFile[0],-2,NULL,FILE_CURRENT);
			*bytesRead -= 2;
		}
		
		comp-> uData(((BYTE*)buffer),*bytesRead, &outbuff, &outbuffersize); 
		cout << "ResoreImage, Initial: " << *bytesRead << " Final: " << outbuffersize << " ";

		readSize += *bytesRead;
		writeSize += outbuffersize;

		tValue = outbuffersize - 500;
		while (tValue > 0)
		{
			cout << "*";
			tValue -= 100;
		}

		cout << endl;

		 *bytesRead = outbuffersize; //this was here 
		//returnwrite = WriteFile(hFile[1],outbuff,outbuffersize,bytesRead,NULL);//this is the correct one
	    //returnwrite = WriteFile(hFile[1],buffer,bufferSize,bytesRead,NULL);//origial code
		//returnwrite = WriteFile(hFile[1],buffer,outbuffersize,bytesRead,NULL);//fails to read		
		 //cout << "Buffer size: " << outbuffersize << endl;
		cout <<"Read in : "<< *bytesRead<< endl;

/*			cout << "File: " << hFile[1] << endl
				 << "Buffer: \"" << outbuff << "\"" << endl
				 << "oBuffSize: " << outbuffersize << endl;
//				 << "bytesWritten: " << *bytesRead << endl;*/
		returnwrite = WriteFile(hFile[1],outbuff,outbuffersize,bytesRead,NULL);//this is correct!!
		cout <<"Read in after Write: "<< *bytesRead<< endl;
		cout << "return write: " << returnwrite << "  bytesRead: " << *bytesRead << endl;
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),0, message,200,NULL);
		cout << "Error Message : " << message << endl;

		//if (false == returnwrite)
		//{
//			cout << "File: " << hFile[1] << endl
				// << "Buffer: \"" << outbuff << "\"" << endl
//				 << "oBuffSize: " << outbuffersize << endl
//				 << "bytesWritten: " << *bytesRead << endl;
		//}

		//dumpbyte(outbuff,10);
		//dumpbyte(outbuff+(outbuffersize-10),10);

		delete[] outbuff;

		//as long as bytesRead==sectorSize the commands
		//completed successfully
	}	
	delete bytesRead;
	delete [] buffer;

	cout << readSize << " bytes read from image file" << endl;
//.........这里部分代码省略.........
开发者ID:janemiceli,项目名称:WinImg,代码行数:101,代码来源:image.cpp


示例3: fopen

bool CCodeProcessor::TryBuild( const char *rootdir, const char *filename, unsigned char *buffer, int filelength )
{
//	vprintf( "trying build\n" );

	FILE *fp;
	fp = fopen( filename, "wb" );
	if ( !fp )
	{
		assert( 0 );
		return false;
	}

	fwrite( buffer, filelength, 1, fp );
	fclose( fp );

	// if build is successful, return true
	//
	//	return true;
	char commandline[ 512 ];
	char directory[ 512 ];

	sprintf( directory, rootdir );

	//	sprintf( commandline, "msdev engdll.dsw /MAKE \"quiver - Win32 GL Debug\" /OUT log.txt" );

	// Builds the default configuration
	sprintf( commandline, "\"C:\\Program Files\\Microsoft Visual Studio\\Common\\MSDev98\\Bin\\msdev.exe\" %s /MAKE \"%s\" /OUT log.txt", m_szDSP, m_szConfig );

	PROCESS_INFORMATION pi;
	memset( &pi, 0, sizeof( pi ) );

	STARTUPINFO si;
	memset( &si, 0, sizeof( si ) );
	si.cb = sizeof( si );

	if ( !CreateProcess( NULL, commandline, NULL, NULL, TRUE, 0, NULL, directory, &si, &pi ) )
	{
LPVOID lpMsgBuf;
FormatMessage( 
    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    FORMAT_MESSAGE_FROM_SYSTEM | 
    FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &lpMsgBuf,
    0,
    NULL 
);
// Process any inserts in lpMsgBuf.
// ...
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );
		return false;
	}

	// Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

	bool retval = false;
	DWORD exitCode = -1;
	if ( GetExitCodeProcess( pi.hProcess, &exitCode ) )
	{
		if ( !exitCode )
		{
			retval = true;
		}
	}
	
    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );

	return retval;
}
开发者ID:RaisingTheDerp,项目名称:raisingthebar,代码行数:77,代码来源:processmodule.cpp


示例4: UpdateXMLData

bool UpdateXMLData(const Category cat, const char *redirect_url /*= 0*/, int recurse_count /*=0*/) {
	
	if(recurse_count > MAX_REDIRECT_RECURSE) {
		PUShowMessageT(TranslateT("Updater: Error getting data - too many redirects"), SM_WARNING);
		return false;
	}

	NETLIBHTTPREQUEST req = {0};
	NETLIBHTTPHEADER etag_hdr = {0};

	if(OldXMLDataExists(cat)) {
		// ensure backend not checked more than once every MIN_XMLDATA_AGE hours
		long age = OldXMLDataAge(cat);
		if(age >= 0 && age < MIN_XMLDATA_AGE)	{	// get it only if our file is at least 8 hours old
#ifdef DEBUG_HTTP_POPUPS
			char buff[512];
			sprintf(buff, "XML Data is recent (%d hours old) - not downloading, using local copy", age);
			PUShowMessage(buff, SM_NOTIFY);
#endif

			return LoadOldXMLData(cat, false);
		}

		// add ETag header for conditional get
		DBCONTACTGETSETTING cgs;
		DBVARIANT dbv;
		cgs.szModule = MODULE;
		char buff[256];
		strcpy(buff, "DataETag_");
		strcat(buff, category_files[cat]);
		cgs.szSetting = buff;
		cgs.pValue = &dbv;
		if(!CallService(MS_DB_CONTACT_GETSETTING, 0, (LPARAM)&cgs)) {
			req.headersCount = 1;
			req.headers = &etag_hdr;
			etag_hdr.szName = "If-None-Match";
			etag_hdr.szValue = _strdup(dbv.pszVal);
			DBFreeVariant(&dbv);
		}
	}

	req.cbSize = sizeof(req);
	req.requestType = REQUEST_GET;
	char URL[MAX_PATH];
	if(!redirect_url) {
		strcpy(URL, MIM_BACKEND_URL_PREFIX);
		strcat(URL, category_files[cat]);
		strcat(URL, ".bz2");
	} else {
		strcpy(URL, redirect_url);
	}
	req.szUrl = URL;
	req.flags = NLHRF_HTTP11;
	req.nlc = hNetlibHttp;

	if (CallService(MS_SYSTEM_GETVERSION, 0, 0) >= PLUGIN_MAKE_VERSION(0,9,0,5))
		req.flags |= NLHRF_PERSISTENT | NLHRF_REDIRECT;

	NETLIBHTTPREQUEST *resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser, (LPARAM)&req);
	free(etag_hdr.szValue);

	if (!resp) 
	{
		hNetlibHttp = NULL;
		if (!Miranda_Terminated())
		{
			int err = GetLastError();
			if (err) 
			{
				TCHAR buff[512];
				int len = mir_sntprintf(buff, SIZEOF(buff), TranslateT("Failed to download XML data: "));
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, err, 0, buff + len, 512 - len, 0);
				ShowError(buff);
				//MessageBox(0, buff + len, TranslateT("Updater: Error Downloading XML Data"), MB_OK | MB_ICONWARNING);
			} 
			else 
			{
				ShowError(TranslateT("Failed to download XML data - Response is NULL"));
				//MessageBox(0, TranslateT("Error downloading XML data...\nResponse is NULL"), TranslateT("Updater Error"), MB_OK | MB_ICONWARNING);
				NLog("Failed to download XML data - Response is NULL");
			}
		}
		return LoadOldXMLData(cat, false);
	} 
	else if (resp->resultCode == 304) { // 'Not Modified' response
		hNetlibHttp = resp->nlc;
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
		resp = 0;
#ifdef DEBUG_HTTP_POPUPS
		PUShowMessage("XML Data unchanged - using local copy", SM_NOTIFY);
#endif

		// mark data as current
		return LoadOldXMLData(cat, true);
	} else if(resp->resultCode >= 300 && resp->resultCode < 400) { // redirect response
		hNetlibHttp = resp->nlc;
		// get new location
		bool ret = false;
		for(int i = 0; i < resp->headersCount; i++) {
			//MessageBox(0, resp->headers[i].szValue, resp->headers[i].szName, MB_OK);
//.........这里部分代码省略.........
开发者ID:darkscout,项目名称:sje-miranda-plugins,代码行数:101,代码来源:xmldata.cpp


示例5: FormatError

/////////////////////////////////////////////////////////////////////////////
//++
//
//  FormatError
//
//  Description:
//      Format an error.
//
//  Arguments:
//      rstrError   String in which to return the error message.
//      dwError     Error code to format.
//
//  Return Value:
//      None.
//
//--
/////////////////////////////////////////////////////////////////////////////
void
FormatError(
      CString & rstrErrorInout
    , DWORD     dwErrorIn
    )
{
    DWORD   cch;
    TCHAR   szError[ 512 ];

    //
    // Format the NT status code from CLUSAPI.  This is necessary
    // for the cases where cluster messages haven't been added to
    // the system message file yet.
    //

    cch = FormatMessage(
                      FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS
                    , ::GetModuleHandle( _T( "CLUSAPI.DLL" ) )
                    , dwErrorIn
                    , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
                    , szError
                    , RTL_NUMBER_OF( szError )
                    , 0
                    );
    if ( cch == 0 )
    {
        cch = FormatMessage(
                          FORMAT_MESSAGE_FROM_SYSTEM
                        , NULL
                        , dwErrorIn
                        , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
                        , szError
                        , RTL_NUMBER_OF( szError )
                        , 0
                        );
        if ( cch == 0 )
        {
            //
            // Format the NT status code from NTDLL since this hasn't been
            // integrated into the system yet.
            //

            cch = FormatMessage(
                              FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS
                            , ::GetModuleHandle( _T( "NTDLL.DLL" ) )
                            , dwErrorIn
                            , MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)
                            , szError
                            , RTL_NUMBER_OF( szError )
                            , 0
                            );
        }  // if:  error formatting status code from system
    }  // if:  error formatting status code from ClusApi

    if ( cch > 0 )
    {
        rstrErrorInout = szError;
    }  // if:  no error
    else
    {
        TRACE( _T( "FormatError() - Error 0x%08.8x formatting string for error code 0x%08.8x\n" ), GetLastError(), dwErrorIn );
        rstrErrorInout.Format( _T( "Error 0x%08.8x" ), dwErrorIn );
    }  // else:  error formatting the message

}  //*** FormatError
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:82,代码来源:File+Share+SampleEx.cpp


示例6: Fatal

static void Fatal(DWORD dw, wchar_t* message, ...) 
{
	void *lpDisplayBuf, *lpMsgBuf;
	
	if(dw == 0) {
		// If no return code was specified, we assume that the message
		// contains a function name that failed. In that case, we retrieve
		// the system error message for the last-error code
		dw = GetLastError();
		
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			dw,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(wchar_t*) &lpMsgBuf,
			0,
			NULL
		);

		// Allocate our buffer for the error message.
		lpDisplayBuf = (void*)LocalAlloc(
			LMEM_ZEROINIT,
			(lstrlenW((const wchar_t*)lpMsgBuf) + lstrlenW((const wchar_t*)message) + 47) * sizeof(wchar_t)
		);
		_snwprintf(
			(wchar_t*)lpDisplayBuf,
			LocalSize(lpDisplayBuf) / sizeof(wchar_t),
			L"FATAL: %s failed with error %d: %s",
			message,
			dw,
			lpMsgBuf
		);
	} else {
		// Otherwise, we assume that the error message is a format string.
		va_list args = NULL;
		
		// Allocate buffer for our resulting format string.
		lpMsgBuf = (void*)LocalAlloc(
			LMEM_ZEROINIT,
			(lstrlenW((const wchar_t*)message) + 8) * sizeof(wchar_t)
		);
		_snwprintf(
			(wchar_t*)lpMsgBuf,
			LocalSize(lpMsgBuf) / sizeof(wchar_t),
			L"FATAL: %s",
			message
		);
		
		// Might as well use the maximum allowed buffer, since there's no way I know of the
		// get the size of the resulting buff.
		lpDisplayBuf = (void*)LocalAlloc(LMEM_ZEROINIT, 4096 * sizeof(wchar_t));
		memset(lpDisplayBuf, 0, 4096 * sizeof(wchar_t));
		va_start(args, lpMsgBuf);
		_vsnwprintf(
			(wchar_t*)lpDisplayBuf,
			4096,
			lpMsgBuf,
			args
		);
		va_end(args);
	}
	MessageBoxW(NULL, (const wchar_t*)lpDisplayBuf, L"Fatal Error", MB_OK | MB_ICONERROR);
	LocalFree(lpMsgBuf);
	LocalFree(lpDisplayBuf);
	ExitProcess(dw); 
}
开发者ID:daleathan,项目名称:depends-launcher,代码行数:67,代码来源:depends-launcher.c


示例7: winMWExtWMWindowProc


//.........这里部分代码省略.........
        winDebug ("winMWExtWMWindowProc - WM_*KEYUP\n");
#endif

        /* Pass the message to the root window */
        SendMessage (hwndScreen, message, wParam, lParam);
        return 0;

    case WM_HOTKEY:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_HOTKEY\n");
#endif

        /* Pass the message to the root window */
        SendMessage (hwndScreen, message, wParam, lParam);
        return 0;

    case WM_PAINT:

        /* BeginPaint gives us an hdc that clips to the invalidated region */
        hdcUpdate = BeginPaint (hwnd, &ps);

        /* Try to copy from the shadow buffer */
        if (!BitBlt (hdcUpdate,
                     ps.rcPaint.left, ps.rcPaint.top,
                     ps.rcPaint.right - ps.rcPaint.left,
                     ps.rcPaint.bottom - ps.rcPaint.top,
                     pRLWinPriv->hdcShadow,
                     ps.rcPaint.left, ps.rcPaint.top,
                     SRCCOPY))
        {
            LPVOID lpMsgBuf;

            /* Display a fancy error message */
            FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
                           FORMAT_MESSAGE_FROM_SYSTEM |
                           FORMAT_MESSAGE_IGNORE_INSERTS,
                           NULL,
                           GetLastError (),
                           MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                           (LPTSTR) &lpMsgBuf,
                           0, NULL);

            ErrorF ("winMWExtWMWindowProc - BitBlt failed: %s\n",
                    (LPSTR)lpMsgBuf);
            LocalFree (lpMsgBuf);
        }

        /* EndPaint frees the DC */
        EndPaint (hwnd, &ps);
        break;

    case WM_ACTIVATE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_ACTIVATE\n");
#endif
        if (LOWORD(wParam) != WA_INACTIVE)
        {
            if (winIsInternalWMRunning(pScreenInfo))
            {
#if 0
                /* Raise the window to the top in Z order */
                wmMsg.msg = WM_WM_RAISE;
                if (fWMMsgInitialized)
                    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
#endif
                /* Tell our Window Manager thread to activate the window */
开发者ID:miettal,项目名称:armadillo420_standard_linux314,代码行数:67,代码来源:winwin32rootlesswndproc.c


示例8: PrepareEnvOptions

int ScriptController::Execute()
{
	PrepareEnvOptions(NULL);
	PrepareArgs();

	int iExitCode = 0;
	int pipein;

#ifdef CHILD_WATCHDOG
	bool bChildConfirmed = false;
	while (!bChildConfirmed && !m_bTerminated)
	{
#endif

#ifdef WIN32
	// build command line

	char* szCmdLine = NULL;
	if (m_szArgs)
	{
		char szCmdLineBuf[2048];
		int iUsedLen = 0;
		for (const char** szArgPtr = m_szArgs; *szArgPtr; szArgPtr++)
		{
			snprintf(szCmdLineBuf + iUsedLen, 2048 - iUsedLen, "\"%s\" ", *szArgPtr);
			iUsedLen += strlen(*szArgPtr) + 3;
		}
		szCmdLineBuf[iUsedLen < 2048 ? iUsedLen - 1 : 2048 - 1] = '\0';
		szCmdLine = szCmdLineBuf;
	}
	else
	{
		szCmdLine = m_szCmdLine;
	}
	
	// create pipes to write and read data
	HANDLE hReadPipe, hWritePipe;
	SECURITY_ATTRIBUTES SecurityAttributes;
	memset(&SecurityAttributes, 0, sizeof(SecurityAttributes));
	SecurityAttributes.nLength = sizeof(SecurityAttributes);
	SecurityAttributes.bInheritHandle = TRUE;

	CreatePipe(&hReadPipe, &hWritePipe, &SecurityAttributes, 0);

	SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);

	STARTUPINFO StartupInfo;
	memset(&StartupInfo, 0, sizeof(StartupInfo));
	StartupInfo.cb = sizeof(StartupInfo);
	StartupInfo.dwFlags = STARTF_USESTDHANDLES;
	StartupInfo.hStdInput = 0;
	StartupInfo.hStdOutput = hWritePipe;
	StartupInfo.hStdError = hWritePipe;

	PROCESS_INFORMATION ProcessInfo;
	memset(&ProcessInfo, 0, sizeof(ProcessInfo));

	char* szEnvironmentStrings = m_environmentStrings.GetStrings();

	BOOL bOK = CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, szEnvironmentStrings, m_szWorkingDir, &StartupInfo, &ProcessInfo);
	if (!bOK)
	{
		DWORD dwErrCode = GetLastError();
		char szErrMsg[255];
		szErrMsg[255-1] = '\0';
		if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErrCode, 0, szErrMsg, 255, NULL))
		{
			PrintMessage(Message::mkError, "Could not start %s: %s", m_szInfoName, szErrMsg);
		}
		else
		{
			PrintMessage(Message::mkError, "Could not start %s: error %i", m_szInfoName, dwErrCode);
		}
		if (!Util::FileExists(m_szScript))
		{
			PrintMessage(Message::mkError, "Could not find file %s", m_szScript);
		}
		free(szEnvironmentStrings);
		return -1;
	}

	free(szEnvironmentStrings);

	debug("Child Process-ID: %i", (int)ProcessInfo.dwProcessId);

	m_hProcess = ProcessInfo.hProcess;

	// close unused "write" end
	CloseHandle(hWritePipe);

	pipein = _open_osfhandle((intptr_t)hReadPipe, _O_RDONLY);

#else

	int p[2];
	int pipeout;

	// create the pipe
	if (pipe(p))
	{
//.........这里部分代码省略.........
开发者ID:ta264,项目名称:nzbget_svn,代码行数:101,代码来源:Script.cpp


示例9: defined

void SocketLayer::SetSocketOptions( SOCKET listenSocket)
{
	int sock_opt = 1;
	// // On Vista, can get WSAEACCESS (10013)
	/*
	if ( setsockopt( listenSocket, SOL_SOCKET, SO_REUSEADDR, ( char * ) & sock_opt, sizeof ( sock_opt ) ) == -1 )
	{
	#if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG) && !defined(X360)
	DWORD dwIOError = GetLastError();
	LPVOID messageBuffer;
	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
	NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
	( LPTSTR ) & messageBuffer, 0, NULL );
	// something has gone wrong here...
	RAKNET_DEBUG_PRINTF( "setsockopt(SO_REUSEADDR) failed:Error code - %d\n%s", dwIOError, messageBuffer );
	//Free the buffer.
	LocalFree( messageBuffer );
	#endif
	}
	*/

	// This doubles the max throughput rate
	sock_opt=1024*256;
	setsockopt(listenSocket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );

	// Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails.
	sock_opt=0;
	setsockopt(listenSocket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) );

#if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3)
	// This doesn't make much difference: 10% maybe
	// Not supported on console 2
	sock_opt=1024*16;
	setsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );
#endif

	/*
	#ifdef _WIN32
		unsigned long nonblocking = 1;
		ioctlsocket( listenSocket, FIONBIO, &nonblocking );
	#elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)
                                                                                                            
	#else
		fcntl( listenSocket, F_SETFL, O_NONBLOCK );
	#endif
	*/

	// Set broadcast capable
	sock_opt=1;
	if ( setsockopt( listenSocket, SOL_SOCKET, SO_BROADCAST, ( char * ) & sock_opt, sizeof( sock_opt ) ) == -1 )
		{
#if defined(_WIN32) && defined(_DEBUG)
		DWORD dwIOError = GetLastError();
		// On Vista, can get WSAEACCESS (10013)
		// See http://support.microsoft.com/kb/819124
		// http://blogs.msdn.com/wndp/archive/2007/03/19/winsock-so-exclusiveaddruse-on-vista.aspx
		// http://msdn.microsoft.com/en-us/library/ms740621(VS.85).aspx
#if !defined(_XBOX) && !defined(X360)
		LPVOID messageBuffer;
		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
			( LPTSTR ) & messageBuffer, 0, NULL );
		// something has gone wrong here...
		RAKNET_DEBUG_PRINTF( "setsockopt(SO_BROADCAST) failed:Error code - %d\n%s", dwIOError, messageBuffer );
		//Free the buffer.
		LocalFree( messageBuffer );
#endif
#endif

		}
}
开发者ID:Hamcha,项目名称:facilitator,代码行数:71,代码来源:SocketLayer.cpp


示例10: winTopLevelWindowProc


//.........这里部分代码省略.........
        /* BeginPaint gives us an hdc that clips to the invalidated region */
        hdcUpdate = BeginPaint(hwnd, &ps);
        /* Avoid the BitBlt's if the PAINTSTRUCT is bogus */
        if (ps.rcPaint.right == 0 && ps.rcPaint.bottom == 0 &&
                ps.rcPaint.left == 0 && ps.rcPaint.top == 0) {
            EndPaint(hwnd, &ps);
            return 0;
        }

#ifdef XWIN_GLX_WINDOWS
        if (pWinPriv->fWglUsed) {
            /*
               For regions which are being drawn by GL, the shadow framebuffer doesn't have the
               correct bits, so don't bitblt from the shadow framebuffer

               XXX: For now, just leave it alone, but ideally we want to send an expose event to
               the window so it really redraws the affected region...
             */
            ValidateRect(hwnd, &(ps.rcPaint));
        }
        else
#endif
            /* Try to copy from the shadow buffer */
            if (!BitBlt(hdcUpdate,
                        ps.rcPaint.left, ps.rcPaint.top,
                        ps.rcPaint.right - ps.rcPaint.left,
                        ps.rcPaint.bottom - ps.rcPaint.top,
                        s_pScreenPriv->hdcShadow,
                        ps.rcPaint.left + pWin->drawable.x,
                        ps.rcPaint.top + pWin->drawable.y, SRCCOPY)) {
                LPVOID lpMsgBuf;

                /* Display a fancy error message */
                FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                              (LPTSTR) &lpMsgBuf, 0, NULL);

                ErrorF("winTopLevelWindowProc - BitBlt failed: %s\n",
                       (LPSTR) lpMsgBuf);
                LocalFree(lpMsgBuf);
            }

        /* EndPaint frees the DC */
        EndPaint(hwnd, &ps);
        return 0;

    case WM_MOUSEMOVE:
        /* Unpack the client area mouse coordinates */
        ptMouse.x = GET_X_LPARAM(lParam);
        ptMouse.y = GET_Y_LPARAM(lParam);

        /* Translate the client area mouse coordinates to screen coordinates */
        ClientToScreen(hwnd, &ptMouse);

        /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
        ptMouse.x -= GetSystemMetrics(SM_XVIRTUALSCREEN);
        ptMouse.y -= GetSystemMetrics(SM_YVIRTUALSCREEN);

        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
开发者ID:sheldonrobinson,项目名称:VcXsrv,代码行数:66,代码来源:winmultiwindowwndproc.c


示例11: DisplayErrorMsg

VOID
DisplayErrorMsg(
    LONG msgId,
    ...
    )
/*++

Routine Description:

    This routine displays the error message correspnding to
    the error indicated by msgId.

Arguments:

    msgId - the errorId. This is either the Win32 status code or the message ID.

Return Value:

    None

--*/
{
    
    va_list args;
    LPWSTR lpMsgBuf;

    va_start( args, msgId );
    
    if (FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
        NULL,
        MSG_ERROR,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        NULL
        ))
    {
        wprintf( L"%ws", lpMsgBuf );
        LocalFree( lpMsgBuf );
    }

    if (FormatMessage(
        (msgId >= MSG_FIRST_MESSAGE_ID ? FORMAT_MESSAGE_FROM_HMODULE :
                                        FORMAT_MESSAGE_FROM_SYSTEM)
         | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        msgId,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        &args
        ))
    {
        wprintf( L" %ws \n", (LPSTR)lpMsgBuf );
        LocalFree( lpMsgBuf );
    } else {
        if (NtDllHandle == INVALID_HANDLE_VALUE) {
            NtDllHandle = GetModuleHandle( L"NTDLL" );
        }
        
        if (FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
            (LPVOID)NtDllHandle,
            msgId,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
            (LPWSTR) &lpMsgBuf,
            0,
            &args))
        {
            wprintf( L" %ws \n", (LPSTR)lpMsgBuf );
            LocalFree( lpMsgBuf );
        } else {
            wprintf( L"Unable to format message for id %x - %x\n", msgId, GetLastError( ));
        }
    }
    
    va_end( args );
}
开发者ID:Nevermore2015,项目名称:ndas4windows,代码行数:79,代码来源:utility.c


示例12: switch

void win_socket::get_error_text(char* buf, size_t buf_size)
{
    char* msg; 
    char  msgbuf[64];

    switch(errcode) { 
      case ok:
        msg = "ok";
        break;
      case not_opened:
        msg = "socket not opened";
        break;
      case bad_address: 
        msg = "bad address";
        break;
      case connection_failed: 
        msg = "exceed limit of attempts of connection to server";
        break;
      case broken_pipe:
        msg = "connection is broken";
        break; 
      case invalid_access_mode:
        msg = "invalid access mode";
        break;
      default: 
#ifndef PHAR_LAP
        {
          int   len;
#if defined(_WINCE) || defined(UNICODE)
          wchar_t cnvBuf[CNV_BUF_SIZE];
          FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                        NULL,
                        errcode,
                        0,
                        cnvBuf,
                        CNV_BUF_SIZE-1,
                        NULL);
          cnvBuf[CNV_BUF_SIZE-1] = '\0';
          len = wcstombs(buf, cnvBuf, buf_size);
#else
          len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                              NULL,
                              errcode,
                              0,
                              buf,
                              (DWORD)buf_size-1,
                              NULL);
#endif
          if (len == 0) { 
              sprintf(msgbuf, "unknown error code %u", errcode);
              msg = msgbuf;
          } else { 
              return;
          }
        }
#else
        sprintf(msgbuf, "System error code: %u", errcode);
        msg = msgbuf;
#endif
    }
    strncpy(buf, msg, buf_size-1);
    buf[buf_size-1] = '\0';
}
开发者ID:nakijun,项目名称:FusionDB,代码行数:63,代码来源:w32sock.cpp


示例13: GETOBJREF


//.........这里部分代码省略.........
// Old object ref tcp:\neo0001.$z123/18650:ObjectName
//
				strcpy(objRef, srvrObjRef);
				pCheck = objRef + 5;
				if ((pIpAddress = strtok(pCheck, ".")) != NULL)
				{
					strtok(NULL, "/");
					if ((pPortNumber = strtok(NULL, ":")) != NULL)
					{
						if ((pObjectName = strtok(NULL, ":")) != NULL)
						{
							sprintf( fwsrvrObjRef, "tcp:%s/%s:%s", pIpAddress,pPortNumber,pObjectName);
						}
					}
					srvrSegName = pIpAddress;
				}
			}
		}
		pConnection->setGetObjRefHdlOutput(fwsrvrObjRef, dialogueId, dataSource, &userSid, &versionList, srvrNodeId, srvrProcessId, timestamp);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASParamError_exn_ :
	// Added check to see if No CPUs or Invalid CPU list are set for MXCS server to start then return 
	// error back to client as param error then parse the error in client to return proper error message.
		pCheck = strstr(exception_.u.ASParamError.ErrorText, "CPU" );
		if (pCheck == NULL)
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PROGRAM_ERROR, exception_.exception_nr,
				exception_.u.ASParamError.ErrorText);
		else
			pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_NO_SRVR_AVAILABLE, 0,
				exception_.u.ASNotAvailable.ErrorText);
		break;	
	case odbcas_ASSvc_GetObjRefHdl_LogonUserFailure_exn_ :
		PVOID lpMsgBuf;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
				NULL,
				exception_.u.LogonUserFailure.errorCode,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // Default language
				(LPTSTR) &lpMsgBuf,
				0,
				NULL);
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_UNABLE_TO_LOGON,
			exception_.u.LogonUserFailure.errorCode,
			 (char *)lpMsgBuf);
		LocalFree(lpMsgBuf);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASNotAvailable_exn_ :
		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_ASSOC_SRVR_NOT_AVAILABLE, 0,
			exception_.u.ASNotAvailable.ErrorText);
		break;
	case odbcas_ASSvc_GetObjRefHdl_DSNotAvailable_exn_:
		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_DS_NOT_AVAILABLE,0L,	
			exception_.u.DSNotAvailable.ErrorText);
		break;
	case odbcas_ASSvc_GetObjRefHdl_PortNotAvailable_exn_:
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PORT_NOT_AVAILABLE);
		break;
	case odbcas_ASSvc_GetObjRefHdl_InvalidUser_exn_:
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_28_000);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASTimeout_exn_ :
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_S1_T00);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASNoSrvrHdl_exn_ :
		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_NO_SRVR_AVAILABLE, 0,
			exception_.u.ASNotAvailable.ErrorText);
		break;
开发者ID:AlexPeng19,项目名称:incubator-trafodion,代码行数:67,代码来源:netconnect.cpp


示例14: WSA_perror


//.........这里部分代码省略.........
            break;
        case WSAESTALE:
            usMsgNum = IDS_WSAESTALE;
            break;
        case WSAEINVAL:
            usMsgNum = IDS_WSAEINVAL;
            break;
        case WSAEMFILE:
            usMsgNum = IDS_WSAEMFILE;
            break;
        case WSAELOOP:
            usMsgNum = IDS_WSAELOOP;
            break;
        case WSAEREMOTE:
            usMsgNum = IDS_WSAEREMOTE;
            break;
        case WSAENOTSOCK:
            usMsgNum = IDS_WSAENOTSOCK;
            break;
        case WSAEADDRNOTAVAIL:
            usMsgNum = IDS_WSAEADDRNOTAVAIL;
            break;
        case WSAEADDRINUSE:
            usMsgNum = IDS_WSAEADDRINUSE;
            break;
        case WSAEAFNOSUPPORT:
            usMsgNum = IDS_WSAEAFNOSUPPORT;
            break;
        case WSAESOCKTNOSUPPORT:
            usMsgNum = IDS_WSAESOCKTNOSUPPORT;
            break;
        case WSAEPROTONOSUPPORT:
            usMsgNum = IDS_WSAEPROTONOSUPPORT;
            break;
        case WSAENOBUFS:
            usMsgNum = IDS_WSAENOBUFS;
            break;
        case WSAETIMEDOUT:
            usMsgNum = IDS_WSAETIMEDOUT;
            break;
        case WSAEISCONN:
            usMsgNum = IDS_WSAEISCONN;
            break;
        case WSAENOTCONN:
            usMsgNum = IDS_WSAENOTCONN;
            break;
        case WSAENOPROTOOPT:
            usMsgNum = IDS_WSAENOPROTOOPT;
            break;
        case WSAECONNRESET:
            usMsgNum = IDS_WSAECONNRESET;
            break;
        case WSAECONNABORTED:
            usMsgNum = IDS_WSAECONNABORTED;
            break;
        case WSAENETDOWN:
            usMsgNum = IDS_WSAENETDOWN;
            break;
        case WSAENETRESET:
            usMsgNum = IDS_WSAENETRESET;
            break;
        case WSAECONNREFUSED:
            usMsgNum = IDS_WSAECONNREFUSED;
            break;
        case WSAEHOSTDOWN:
            usMsgNum = IDS_WSAEHOSTDOWN;
            break;
        case WSAEHOSTUNREACH:
            usMsgNum = IDS_WSAEHOSTUNREACH;
            break;
        case WSAEPROTOTYPE:
            usMsgNum = IDS_WSAEPROTOTYPE;
            break;
        case WSAEOPNOTSUPP:
            usMsgNum = IDS_WSAEOPNOTSUPP;
            break;
        case WSAENETUNREACH:
            usMsgNum = IDS_WSAENETUNREACH;
            break;
        case WSAETOOMANYREFS:
            usMsgNum = IDS_WSAETOOMANYREFS;
            break;
        default:
            return(0);
    }

    if (!(msglen = FormatMessage(
               FORMAT_MESSAGE_FROM_HMODULE,
               (LPVOID)SockModuleHandle,
               usMsgNum,
               0L,
               perr,
               MAX_MSGTABLE,
               NULL))) {
        return(0);
    }

    fprintf(stderr, "-> %s:%s\n", yourmsg, perr);
    return(1);
}
开发者ID:mingpen,项目名称:OpenNT,代码行数:101,代码来源:w_perror.c


示例15: main

int main(int argc, char *argv[])
{
    char *filepath, *cmd;
    char fn[SIZE];
    int i;
    int fd, fd_start, fd_end, fd_ret, fd_stdout, fd_stderr;
    time_t now;

#ifdef _WINDOWS
    char full_cmd[SIZE];
    TCHAR w_cmd[SIZE];
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    DWORD ret;
    LPVOID lpMsgBuf;
    char msg[SIZE];
#else
    pid_t pid;
    int ret;
#endif

    if (argc != 3) {
        fprintf(stderr, "%s output_filepath command\n", argv[0]);
        return -1;
    }
    filepath = argv[1];
    cmd = argv[2];
    ret = 127;

    fd = -1;
    fd_start = -1;
    fd_end = -1;
    fd_ret = -1;
    fd_stdout = -1;
    fd_stderr = -1;
    i = 0;
    while (ext[i] != NULL) {
        sprintf(fn, "%s.%s", filepath, ext[i]);
        fd = open(fn, O_WRONLY | O_BINARY | O_TRUNC);
        if (fd < 0) {
            fprintf(stderr, "%s: %s\n", fn, strerror(errno));
            return -1;
        }
        if (i == 0)
            fd_start = fd;
        else if (i == 1)
            fd_end = fd;
        else if (i == 2)
            fd_ret = fd;
        else if (i == 3)
            fd_stdout = fd;
        else if (i == 4)
            fd_stderr = fd;
        else
            close(fd);
        i++;
    }

    fflush(stdout);
    fflush(stderr);
    dup2(fd_stdout, 1);
    dup2(fd_stderr, 2);

    now = time(NULL);
    if (write(fd_start, &now, sizeof(now)) < 0)
        fprintf(stderr, "fd_start: %s\n", strerror(errno));
    close(fd_start);

#ifdef _WINDOWS
    ZeroMemory(full_cmd, sizeof(full_cmd));
    ZeroMemory(w_cmd, sizeof(w_cmd));
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    SetLastError(NO_ERROR);

    sprintf(full_cmd, "cmd /q /k \"%s\" & exit !errorlevel!", cmd);
    MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED, full_cmd,
                        strlen(full_cmd), w_cmd, sizeof(w_cmd));

    if (0 == CreateProcess(NULL,        /* no module name (use command line) */
                           w_cmd,       /* name of app to launch */
                           NULL,        /* default process security attributes */
                           NULL,        /* default thread security attributes */
                           TRUE,        /* do not inherit handles from the parent */
                           0,   /* normal priority */
                           NULL,        /* use the same environment as the parent */
                           NULL,        /* launch in the current directory */
                           &si, /* startup information */
                           &pi  /* process information stored upon return */
        )) {
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                      FORMAT_MESSAGE_FROM_SYSTEM |
                      FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPTSTR) & lpMsgBuf, 0, NULL);
        WideCharToMultiByte(CP_ACP, 0, (LPTSTR) lpMsgBuf, -1, msg, SIZE,
                            NULL, NULL);
        fprintf(stderr, "failed to create process for [%s]: %s", cmd, msg);
        LocalFree(lpMsgBuf);
//.........这里部分代码省略.........
开发者ID:hatta0713,项目名称:jobarranger,代码行数:101,代码来源:jobarg_command.c


示例16: htons

SOCKET SocketLayer::CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048 )
{
	(void) blockingSocket;

	int ret;
	SOCKET listenSocket;
	sockaddr_in listenerSocketAddress;
	// Listen on our designated Port#
	listenerSocketAddress.sin_port = htons( port );
#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)
	listenSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_VDP );
#else
	listenSocket = socket( AF_INET, SOCK_DGRAM, 0 );
#endif

	if ( listenSocket == (SOCKET) -1 )
	{
#if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG)
		DWORD dwIOError = GetLastError();
		LPVOID messageBuffer;
		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
			( LPTSTR ) & messageBuffer, 0, NULL );
		// something has gone wrong here...
		RAKNET_DEBUG_PRINTF( "socket(...) failed:Error code - %d\n%s", dwIOError, messageBuffer );
		//Free the buffer.
		LocalFree( messageBuffer );
#endif

		return (SOCKET) -1;
	}

	SetSocketOptions(listenSocket);

	// Fill in the rest of the address structure
	listenerSocketAddress.sin_family = AF_INET;

	if (forceHostAddress && forceHostAddress[0])
	{
//		printf("Force binding %s:%i\n", forceHostAddress, port);
		listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress );
	}
	else
	{
//		printf("Binding any on port %i\n", port);
		listenerSocketAddress.sin_addr.s_addr = INADDR_ANY;
	}

	// bind our name to the socket
	ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) );

	if ( ret <= -1 )
	{
#if defined(_WIN32) && !defined(_XBOX) && !defined(X360)
		DWORD dwIOError = GetLastError();
		if (dwIOError==10048)
		{
			if (sleepOn10048==0)
				return (SOCKET) -1;
			// Vista has a bug where it returns WSAEADDRINUSE (10048) if you create, shutdown, then rebind the socket port unless you wait a while first.
			// Wait, then rebind
			RakSleep(100);

			closesocket(listenSocket);
			listenerSocketAddress.sin_port = htons( port );
			listenSocket = socket( AF_INET, SOCK_DGRAM, 0 );
			if ( listenSocket == (SOCKET) -1 )
				return false;
			SetSocketOptions(listenSocket);

			// Fill in the rest of the address structure
			listenerSocketAddress.sin_family = AF_INET;
			if (forceHostAddress && forceHostAddress[0])
				listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress );
			else
				listenerSocketAddress.sin_addr.s_addr = INADDR_ANY;

			// bind our name to the socket
			ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) );

			if ( ret >= 0 )
				return listenSocket;
		}
		dwIOError = GetLastError();
		LPVOID messageBuffer;
		Form 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ FormatMessageA函数代码示例发布时间:2022-05-30
下一篇:
C++ FormatMagickString函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap