當前位置: 首頁>>代碼示例>>C++>>正文


C++ GetOverlappedResult函數代碼示例

本文整理匯總了C++中GetOverlappedResult函數的典型用法代碼示例。如果您正苦於以下問題:C++ GetOverlappedResult函數的具體用法?C++ GetOverlappedResult怎麽用?C++ GetOverlappedResult使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了GetOverlappedResult函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C++代碼示例。

示例1: co_win32_overlapped_read_completed

co_rc_t co_win32_overlapped_read_completed(co_win32_overlapped_t *overlapped)
{
	BOOL result;

	result = GetOverlappedResult(
		overlapped->handle,
		&overlapped->read_overlapped,
		&overlapped->size,
		FALSE);

	if (result) {
		co_win32_overlapped_read_received(overlapped);
		co_win32_overlapped_read_async(overlapped);
	} else {
		if (GetLastError() == ERROR_BROKEN_PIPE) {
			co_debug("Pipe broken, exiting\n");
			return CO_RC(ERROR);
		}

		co_debug("GetOverlappedResult error %d\n", GetLastError());
	}
	 
	return CO_RC(OK);
}
開發者ID:matt81093,項目名稱:Original-Colinux,代碼行數:24,代碼來源:main.c

示例2: ReadFile

bool
LocalServer::read_data(void* buffer, int len)
{
	OVERLAPPED overlapped;
	overlapped.Offset = 0;
	overlapped.OffsetHigh = 0;
	overlapped.hEvent = 0;
	DWORD bytes;
	BOOL done = ReadFile(m_pipe, buffer, len, &bytes, &overlapped);
	if (done == FALSE) {
		DWORD error = GetLastError();
		if (error != ERROR_IO_PENDING) {
			dprintf(D_ALWAYS, "ReadFileError: %u\n", error);
			return false;
		}
		if (GetOverlappedResult(m_pipe, &overlapped, &bytes, TRUE) == FALSE) {
			dprintf(D_ALWAYS, "GetOverlappedResult error: %u\n", GetLastError());
			return false;
		}
	}
	ASSERT(bytes == len);

	return true;
}
開發者ID:AlainRoy,項目名稱:htcondor,代碼行數:24,代碼來源:local_server.WINDOWS.cpp

示例3: wait

		int wait(HANDLE file, error_code& ec)
		{
			if (ol.hEvent != INVALID_HANDLE_VALUE
				&& WaitForSingleObject(ol.hEvent, INFINITE) == WAIT_FAILED)
			{
				ec.assign(GetLastError(), system_category());
				return -1;
			}

			DWORD ret;
			if (GetOverlappedResult(file, &ol, &ret, false) == 0)
			{
				DWORD last_error = GetLastError();
				if (last_error != ERROR_HANDLE_EOF)
				{
#ifdef ERROR_CANT_WAIT
					TORRENT_ASSERT(last_error != ERROR_CANT_WAIT);
#endif
					ec.assign(last_error, system_category());
					return -1;
				}
			}
			return ret;
		}
開發者ID:pavel-pimenov,項目名稱:flylinkdc-r5xx,代碼行數:24,代碼來源:file.cpp

示例4: EnterCriticalSection

//
// Character received. Inform the owner
//
void CSerialPort::ReceiveChar(CSerialPort* port)
{
    BOOL  bRead = TRUE;
    BOOL  bResult = TRUE;
    DWORD dwError = 0;
    DWORD BytesRead = 0;
    COMSTAT comstat;
    unsigned char RXBuff;

    for (;;)
    {
        //add by liquanhai 2011-11-06  防止死鎖
        if(WaitForSingleObject(port->m_hShutdownEvent,0)==WAIT_OBJECT_0)
            return;

        // Gain ownership of the comm port critical section.
        // This process guarantees no other part of this program
        // is using the port object.

        EnterCriticalSection(&port->m_csCommunicationSync);

        // ClearCommError() will update the COMSTAT structure and
        // clear any other errors.
        ///更新COMSTAT

        bResult = ClearCommError(port->m_hComm, &dwError, &comstat);

        LeaveCriticalSection(&port->m_csCommunicationSync);

        // start forever loop.  I use this type of loop because I
        // do not know at runtime how many loops this will have to
        // run. My solution is to start a forever loop and to
        // break out of it when I have processed all of the
        // data available.  Be careful with this approach and
        // be sure your loop will exit.
        // My reasons for this are not as clear in this sample
        // as it is in my production code, but I have found this
        // solutiion to be the most efficient way to do this.

        ///所有字符均被讀出,中斷循環
        if (comstat.cbInQue == 0)
        {
            // break out when all bytes have been read
            break;
        }

        EnterCriticalSection(&port->m_csCommunicationSync);

        if (bRead)
        {
            ///串口讀出,讀出緩衝區中字節
            bResult = ReadFile(port->m_hComm,		// Handle to COMM port
                               &RXBuff,				// RX Buffer Pointer
                               1,					// Read one byte
                               &BytesRead,			// Stores number of bytes read
                               &port->m_ov);		// pointer to the m_ov structure
            // deal with the error code
            ///若返回錯誤,錯誤處理
            if (!bResult)
            {
                switch (dwError = GetLastError())
                {
                case ERROR_IO_PENDING:
                {
                    // asynchronous i/o is still in progress
                    // Proceed on to GetOverlappedResults();
                    ///異步IO仍在進行
                    bRead = FALSE;
                    break;
                }
                default:
                {
                    // Another error has occured.  Process this error.
                    port->ProcessErrorMessage("ReadFile()");
                    break;
                    //return;///防止讀寫數據時,串口非正常斷開導致死循環一直執行。add by itas109 2014-01-09 與上麵liquanhai添加防死鎖的代碼差不多
                }
                }
            }
            else///ReadFile返回TRUE
            {
                // ReadFile() returned complete. It is not necessary to call GetOverlappedResults()
                bRead = TRUE;
            }
        }  // close if (bRead)

        ///異步IO操作仍在進行,需要調用GetOverlappedResult查詢
        if (!bRead)
        {
            bRead = TRUE;
            bResult = GetOverlappedResult(port->m_hComm,	// Handle to COMM port
                                          &port->m_ov,		// Overlapped structure
                                          &BytesRead,		// Stores number of bytes read
                                          TRUE); 			// Wait flag

            // deal with the error code
            if (!bResult)
//.........這裏部分代碼省略.........
開發者ID:yaoohui,項目名稱:PMSRTest,代碼行數:101,代碼來源:SerialPort.cpp

示例5: Socket_Listener_accept

Socket_Stream Socket_Listener_accept(Socket_Listener self) {
    // Waits for a client to connect, then returns a pointer to the established
    // connection.  The code below is a bit tricky, because Windows expects the
    // call to accept() to happen before the I/O event can be triggered.  For
    // Unix systems, the wait happens first, and then accept() is used to
    // receive the incoming socket afterwards.
    Socket_Stream stream = 0;

    // Begin the call to accept() by creating a new socket and issuing a call 
    // to AcceptEx.
    char buffer[(sizeof(struct sockaddr_in)+16)*2];
    DWORD socklen = sizeof(struct sockaddr_in)+16;
    DWORD read = 0;
    DWORD code = SIO_GET_EXTENSION_FUNCTION_POINTER;
    GUID guid = WSAID_ACCEPTEX;
    LPFN_ACCEPTEX AcceptEx = 0;
    DWORD bytes = 0;
    DWORD len = sizeof(AcceptEx);
    Io_Overlapped op;
    OVERLAPPED* evt = &op.overlapped;

    // Create a new socket for AcceptEx to use when a peer connects.
    SOCKET ls = self->handle;
    SOCKET sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sd < 0) {
        Boot_abort();
    }

    // Get a pointer to the AcceptEx() function.
    WSAIoctl(sd, code, &guid, sizeof(guid), &AcceptEx, len, &bytes, 0, 0);
    
    // Initialize the OVERLAPPED structure that contains the user I/O data used
    // to resume the coroutine when AcceptEx completes. 
    memset(&op, 0, sizeof(op));
    op.coroutine = Coroutine__current;

    // Now call ConnectEx to begin accepting peer connections.  The call will
    // return immediately, allowing this function to yield to the I/O manager.
    if (!AcceptEx(ls, sd, buffer, 0, socklen, socklen, &read, evt)) {
        while (ERROR_IO_PENDING == GetLastError()) {
            // Wait for the I/O manager to yield after polling the I/O
            // completion port, and then get the result.
            Coroutine__iowait();
            SetLastError(ERROR_SUCCESS);
            GetOverlappedResult((HANDLE)sd, evt, &bytes, 1);
        } 
        if (ERROR_SUCCESS != GetLastError()) {
            Boot_abort();
        }
    }
    
    // The following setsockopt() call is needed when calling AcceptEx.  From
    // the MSDN documentation: 
    //
    // When the AcceptEx function returns, the socket sAcceptSocket is in the
    // default state for a connected socket. The socket sAcceptSocket does not
    // inherit the properties of the socket associated with sListenSocket
    // parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket. Use the
    // setsockopt function to set the SO_UPDATE_ACCEPT_CONTEXT option,
    // specifying sAcceptSocket as the socket handle and sListenSocket as the
    // option value.
    if (setsockopt(sd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char const*)&ls, sizeof(ls))) {
        Boot_abort();
    }

    stream = Socket_Stream__init();
    stream->stream = Io_Stream__init(sd, Io_StreamType_SOCKET);
    return stream;
}
開發者ID:mfichman,項目名稱:jogo,代碼行數:69,代碼來源:Listener.c

示例6: RCF_ASSERT

    std::size_t Win32NamedPipeClientTransport::implRead(
        const ByteBuffer &byteBuffer,
        std::size_t bytesRequested)
    {
        // For now, can't go back to sync calls after doing an async call.
        // Limitations with Windows IOCP.
        RCF_ASSERT(!mAsyncMode);

        std::size_t bytesToRead = RCF_MIN(bytesRequested, byteBuffer.getLength());

        BOOL ok = ResetEvent(mhEvent);
        DWORD dwErr = GetLastError();
        RCF_VERIFY(ok, Exception(_RcfError_Pipe(), dwErr));

        OVERLAPPED overlapped = {0};
        overlapped.hEvent = mhEvent;

        DWORD dwRead = 0;
        DWORD dwBytesToRead = static_cast<DWORD>(bytesToRead);

        ok = ReadFile(
            mhPipe, 
            byteBuffer.getPtr(), 
            dwBytesToRead, 
            &dwRead, 
            &overlapped);
        
        dwErr = GetLastError();

        if (!ok)
        {
            RCF_VERIFY( 
                dwErr == ERROR_IO_PENDING ||
                dwErr == WSA_IO_PENDING ||
                dwErr == ERROR_MORE_DATA,
                Exception(_RcfError_ClientReadFail(), dwErr));
        }

        ClientStub & clientStub = *getTlsClientStubPtr();

        DWORD dwRet = WAIT_TIMEOUT;
        while (dwRet == WAIT_TIMEOUT)
        {
            boost::uint32_t timeoutMs = generateTimeoutMs(mEndTimeMs);
            timeoutMs = clientStub.generatePollingTimeout(timeoutMs);

            dwRet = WaitForSingleObject(overlapped.hEvent, timeoutMs);
            dwErr = GetLastError();

            RCF_VERIFY( 
                dwRet == WAIT_OBJECT_0 || dwRet == WAIT_TIMEOUT, 
                Exception(_RcfError_Pipe(), dwErr));

            RCF_VERIFY(
                generateTimeoutMs(mEndTimeMs),
                Exception(_RcfError_ClientReadTimeout()))
                (mEndTimeMs)(bytesToRead);

            if (dwRet == WAIT_TIMEOUT)
            {
                clientStub.onPollingTimeout();
            }
        }
        RCF_ASSERT_EQ(dwRet , WAIT_OBJECT_0);

        dwRead = 0;
        ok = GetOverlappedResult(mhPipe, &overlapped, &dwRead, FALSE);
        dwErr = GetLastError();
        RCF_VERIFY(ok && dwRead > 0, Exception(_RcfError_Pipe(), dwErr));

        onTimedRecvCompleted(dwRead, 0);

        return dwRead;
    }
開發者ID:crazyguymkii,項目名稱:SWGEmuRPCServer,代碼行數:74,代碼來源:Win32NamedPipeClientTransport.cpp

示例7: wxSleep


//.........這裏部分代碼省略.........
            {
                m_gps_fd = 0;
                
                int nwait = 2000;
                while(nwait > 0){
                    wxThread::Sleep(200);                        // stall for a bit
                    
                    if((TestDestroy()) || (m_launcher->m_Thread_run_flag == 0))
                        goto thread_exit;                               // smooth exit
                        
                    nwait -= 200;
                }
            }
        }

        if( (m_io_select == DS_TYPE_INPUT_OUTPUT) || (m_io_select == DS_TYPE_OUTPUT) ) {
                m_outCritical.Enter();
                bool b_qdata = !out_que.empty();
                    
                bool b_break = false;
                while(!b_break && b_qdata){
                    char msg[MAX_OUT_QUEUE_MESSAGE_LENGTH];
                    
//                    printf("wl %d\n", out_que.size());
                    {
                        
                        if(fWaitingOnWrite){
//                            printf("wow\n");
                            dwRes = WaitForSingleObject(osWriter.hEvent, INFINITE);
                            
                            switch(dwRes)
                            {
                                case WAIT_OBJECT_0:
                                    if (!GetOverlappedResult(hSerialComm, &osWriter, &dwWritten, FALSE)) {
                                        if (GetLastError() == ERROR_OPERATION_ABORTED){
                                            //    UpdateStatus("Write aborted\r\n");
                                        }
                                        else{
                                            b_break = true;
                                        }
                                    }
                                    
                                    if (dwWritten != dwToWrite) {
                                        //ErrorReporter("Error writing data to port (overlapped)");
                                    }
                                    else {
                                        // Delayed write completed
                                        fWaitingOnWrite = false;
//                                        printf("-wow\n");
                                    }
                                    break;
                                    
                                //                
                                // wait timed out
                                //
                                case WAIT_TIMEOUT:
                                    break;
                                    
                                case WAIT_FAILED:
                                default:
                                    break;
                            }
                            
                        }
                        if(!fWaitingOnWrite){          // not waiting on Write, OK to issue another
                        
開發者ID:libai245,項目名稱:wht1,代碼行數:66,代碼來源:OCP_DataStreamInput_Thread.cpp

示例8: ADIOI_NTFS_ReadDone

int ADIOI_NTFS_ReadDone(ADIO_Request *request, ADIO_Status *status,
			int *error_code)
{
    DWORD ret_val;
    int done = 0;
    static char myname[] = "ADIOI_NTFS_ReadDone";

    if (*request == ADIO_REQUEST_NULL)
    {
	*error_code = MPI_SUCCESS;
	return 1;
    }

    if ((*request)->queued) 
    {
	(*request)->nbytes = 0;
	ret_val = GetOverlappedResult((*request)->fd, (*request)->handle, &(*request)->nbytes, FALSE);

	if (!ret_val)
	{
	    /* --BEGIN ERROR HANDLING-- */
	    ret_val = GetLastError();
	    if (ret_val == ERROR_IO_INCOMPLETE)
	    {
		done = 0;
		*error_code = MPI_SUCCESS;
	    }
	    else
	    {
		*error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
		    myname, __LINE__, MPI_ERR_IO,
		    "**io", "**io %s", ADIOI_NTFS_Strerror(ret_val));
	    }
	    /* --END ERROR HANDLING-- */
	}
	else 
	{
	    done = 1;		
	    *error_code = MPI_SUCCESS;
	}
    }
    else
    {
	done = 1;
	*error_code = MPI_SUCCESS;
    }
#ifdef HAVE_STATUS_SET_BYTES
    if (done && ((*request)->nbytes != -1))
	MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes);
#endif
    
    if (done) 
    {
	/* if request is still queued in the system, it is also there
	   on ADIOI_Async_list. Delete it from there. */
	if ((*request)->queued) ADIOI_Del_req_from_list(request);
	
	(*request)->fd->async_count--;
	if ((*request)->handle) 
	{
	    if (!CloseHandle(((OVERLAPPED*)((*request)->handle))->hEvent))
	    {
		ret_val = GetLastError();
		*error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
		    myname, __LINE__, MPI_ERR_IO,
		    "**io", "**io %s", ADIOI_NTFS_Strerror(ret_val));
	    }
	    ADIOI_Free((*request)->handle);
	}
	ADIOI_Free_request((ADIOI_Req_node *) (*request));
	*request = ADIO_REQUEST_NULL;
    }
    return done;
}
開發者ID:aosm,項目名稱:openmpi,代碼行數:74,代碼來源:io_romio_ad_ntfs_done.c

示例9: rx_thread


//.........這裏部分代碼省略.........
        dwWaitResult = WaitForSingleObject(goConnect.hEvent, g_timeout_ms);
        if (dwWaitResult == WAIT_TIMEOUT) {
            /* nobody transmitted within timeout period */
#ifdef RADIO_DEBUG
            printf("rx_thread ConnectNamedPipe() WAIT_TIMEOUT\n");
#endif
            radio_pipe_close();
            continue;
        } else if (dwWaitResult != WAIT_OBJECT_0) {
            printf("[41mconnect wait failed %ld[0m\n", GetLastError());
            radio_pipe_close();
            continue;
        }

        /* transmitting side has connected */

        bReadFail = FALSE;
        nbytes = em2_remaining_bytes();
        do { // while (nbytes > 0)...
            if (nbytes > (RX_BUF_SIZE-1))
                nbytes = (RX_BUF_SIZE-1);

            dbg_rx_state = RS__READFILE;
            /* this read is blocking: we're in our own thread */
            b = ReadFile(
                /*HANDLE hFile*/ghRxPipe,
                /*LPVOID lpBuffer*/&rx_buf,
                /*DWORD nNumberOfBytesToRead*/nbytes,
                /*LPDWORD lpNumberOfBytesRead*/&NumberOfBytesRead,
                /*LPOVERLAPPED lpOverlapped*/&goConnect
            );

            if (b == 0) {
                DWORD nbt;
                DWORD e = GetLastError();
                if (e == ERROR_PIPE_LISTENING) {
                    bReadFail = TRUE;
                    printf("ReadFile(): write side disconnected[0m\n");
                    radio_pipe_close();
                    break;
                } else if (e == ERROR_IO_PENDING) {
                    /* read operation is completing asynchronously */
                    b = GetOverlappedResult(
                        /*HANDLE hFile*/ghRxPipe,
                        /*LPOVERLAPPED lpOverlapped*/&goConnect,
                        /*LPDWORD lpNumberOfBytesTransferred*/&nbt,
                        /*BOOL bWait*/TRUE /* blocking */
                    );
                    if (b) {
                        rx_buf_in_idx = nbt;
                    } else {
                        e = GetLastError();
                        printf("[41mGetOverlappedResult() failed %ld[0m\n", e);
                        radio_pipe_close();
                        bReadFail = TRUE;
                        break;
                    }
                } else {
                    if (e == ERROR_INVALID_HANDLE) {
                        /* this likely occurs because rx pipe was closed */
                        printf("[41mReadFile() ERROR_INVALID_HANDLE[0m\n");
                        radio_pipe_close();
                        bReadFail = TRUE;
                        break;
                    } else {
                        printf("[41mReadFile() failed %ld[0m\n", e);
                        radio_pipe_close();
                        bReadFail = TRUE;
                        break;
                    }
                }
            } else {
                // read operation completed synchronously
                rx_buf_in_idx = NumberOfBytesRead;
            }

            rx_buf_out_idx = 0;
            em2_decode_data();

            nbytes = em2_remaining_bytes();
        } while (nbytes > 0);

        if (bReadFail)
            radio.evtdone(RM2_ERR_GENERIC, 0);
        else
            rx_done_isr(0);

        if (ghRxPipe != NULL) {
            printf("thread: rx handle open\n");
            break;
        }
    } // ...for (;;)

    dbg_rx_state = RS__EXITED;
    printf("[41mrx_thread stop[0m\n");
    return -1;
#if 0
#endif /* #if 0 */

}
開發者ID:kaalabs,項目名稱:OpenTag,代碼行數:101,代碼來源:windows_pipe.c

示例10: defined

// Read from the serial port.  Returns only the bytes that are
// already received, up to count.  This always returns without delay,
// returning 0 if nothing has been received
int Serial::Read(void *ptr, int count)
{
	if (!port_is_open) return -1;
	if (count <= 0) return 0;
#if defined(LINUX)
	int n, bits;
	n = read(port_fd, ptr, count);
	if (n < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
	if (n == 0 && ioctl(port_fd, TIOCMGET, &bits) < 0) return -99;
	return n;
#elif defined(MACOSX)
	int n;
	n = read(port_fd, ptr, count);
	if (n < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
	return n;
#elif defined(WINDOWS)
	// first, we'll find out how many bytes have been received
	// and are currently waiting for us in the receive buffer.
	//   http://msdn.microsoft.com/en-us/library/ms885167.aspx
	//   http://msdn.microsoft.com/en-us/library/ms885173.aspx
	//   http://source.winehq.org/WineAPI/ClearCommError.html
	COMSTAT st;
	DWORD errmask=0, num_read, num_request;
	OVERLAPPED ov;
	int r;
	if (!ClearCommError(port_handle, &errmask, &st)) return -1;
	//printf("Read, %d requested, %lu buffered\n", count, st.cbInQue);
	if (st.cbInQue <= 0) return 0;
	// now do a ReadFile, now that we know how much we can read
	// a blocking (non-overlapped) read would be simple, but win32
	// is all-or-nothing on async I/O and we must have it enabled
	// because it's the only way to get a timeout for WaitCommEvent
	num_request = ((DWORD)count < st.cbInQue) ? (DWORD)count : st.cbInQue;
	ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (ov.hEvent == NULL) return -1;
	ov.Internal = ov.InternalHigh = 0;
	ov.Offset = ov.OffsetHigh = 0;
	if (ReadFile(port_handle, ptr, num_request, &num_read, &ov)) {
		// this should usually be the result, since we asked for
		// data we knew was already buffered
		//printf("Read, immediate complete, num_read=%lu\n", num_read);
		r = num_read;
	} else {
		if (GetLastError() == ERROR_IO_PENDING) {
			if (GetOverlappedResult(port_handle, &ov, &num_read, TRUE)) {
				//printf("Read, delayed, num_read=%lu\n", num_read);
				r = num_read;
			} else {
				//printf("Read, delayed error\n");
				r = -1;
			}
		} else {
			//printf("Read, error\n");
			r = -1;
		}
	}
	CloseHandle(ov.hEvent);
	// TODO: how much overhead does creating new event objects on
	// every I/O request really cost?  Would it be better to create
	// just 3 when we open the port, and reset/reuse them every time?
	// Would mutexes or critical sections be needed to protect them?
	return r;
#endif
}
開發者ID:RDju,項目名稱:knobot_soft,代碼行數:67,代碼來源:serial.cpp

示例11: main

int main(int argc, char *argv[])
{
SDL_DisplayMode displayMode;
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
    std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
    return 1;
}
int request = SDL_GetDesktopDisplayMode(0,&displayMode);
SDL_Window *win = SDL_CreateWindow("Hello World!", 0, 0, 333,227, SDL_WINDOW_SHOWN);
if (win == NULL){
    std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
    return 1;
}
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == NULL){
    std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
    return 1;
}
SDL_Rect player_RECT;
        player_RECT.x = 0;   //Смещение полотна по Х
        player_RECT.y = 0;   //Смещение полотна по Y
        player_RECT.w = 333; //Ширина полотна
        player_RECT.h = 227; //Высота полотна

SDL_Rect background_RECT;
        background_RECT.x = 0;
        background_RECT.y = 0;
        background_RECT.w = 333;
        background_RECT.h = 227;

            char bufrd[255], bufwt[255];
            HANDLE ComPort;
            OVERLAPPED olread;
            OVERLAPPED olwrite;
            COMSTAT comstat;
            DWORD mask, tempwrite, tempread, bytesread;


// Block of port openning

int NumofCom = 1;
char NameofCom[5] = "COM1";
char NumofComc[2];
ComPort = CreateFile(NameofCom, GENERIC_READ|GENERIC_WRITE, 0, NULL,OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
olread.hEvent = CreateEvent(NULL,true,true,NULL);

while(ComPort==INVALID_HANDLE_VALUE&&NumofCom<20)
{
    NumofCom++;
    strcpy(NameofCom, "COM");
    itoa(NumofCom,NumofComc, 10);
    strcat(NameofCom, NumofComc);
    ComPort = CreateFile(NameofCom, GENERIC_READ|GENERIC_WRITE, 0, NULL,OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
olread.hEvent = CreateEvent(NULL,true,true,NULL);
}
::std::cout<<NameofCom;

//

if(NumofCom <20)
{

olwrite.hEvent = CreateEvent(NULL,TRUE,TRUE,NULL);
olwrite.Internal = 0;
olwrite.InternalHigh = 0;
strcpy(bufwt, "Hello");
WriteFile(ComPort,bufwt, strlen(bufwt),&tempwrite, &olwrite);
DWORD signal = WaitForSingleObject(olwrite.hEvent, INFINITE);
bool fl;
 //если операция завершилась успешно, установить соответствующий флажок
 if((signal == WAIT_OBJECT_0) && (GetOverlappedResult(ComPort, &olwrite, &tempwrite, true))) fl = true;
 else fl = false;
//вывести состояние операции в строке состояния
 CloseHandle(olwrite.hEvent);
::std::cout<<"Writed!"<<MB_ICONERROR<<" "<<tempwrite<<" "<<fl;

//while()
::std::cout<<"Reading Begin";
olread.hEvent = CreateEvent(NULL,TRUE,TRUE,NULL);
olread.Internal = 0;
olread.InternalHigh = 0;
SetCommMask(ComPort, EV_RXCHAR);
WaitCommEvent(ComPort, &mask, &olread);
::std::cout<<"Char received!";

//problem is here!
signal=WaitForSingleObject(olread.hEvent, INFINITE);
::std::cout<<"Single object received!";

if(signal==WAIT_OBJECT_0)
{
    if(GetOverlappedResult(ComPort, &olread, &tempread, true))
{
      if(mask&EV_RXCHAR)
{
        ::std::cout<<"Start reading!";
    ClearCommError(ComPort, &tempread, &comstat);
    bytesread = comstat.cbInQue;
    if(bytesread)
    ReadFile(ComPort, bufrd, bytesread, &tempread, &olread);
//.........這裏部分代碼省略.........
開發者ID:LevGit,項目名稱:Rep,代碼行數:101,代碼來源:try.cpp

示例12: VideoExcelReportPipeInstanceProc


//.........這裏部分代碼省略.........

				CloseHandle(g_hVideoExcelReportPipeRead);
				g_hVideoExcelReportPipeRead = NULL;

				CloseHandle(g_hVideoExcelReportPipeWrite);
				g_hVideoExcelReportPipeWrite = NULL;

				CloseHandle(g_hVideoExcelReportPipeExit);
				g_hVideoExcelReportPipeExit = NULL;

				return 4;
			}

			if (dwResult == WAIT_OBJECT_0)//讀
			{
				TRACE("\nReceived data or connection request!");
				bReadEvent = FALSE;
			}
			else if (dwResult == WAIT_OBJECT_0 + 1)//寫
			{
				TRACE("\nWrite data!");
			}
			else //WAIT_OBJECT_2:application exit - close handle  default:error
			{
				break;
			}

			//重置事件
			ResetEvent(Event[dwResult-WAIT_OBJECT_0]);

			// Check overlapped results, and if they fail, reestablish 
			// communication for a new client; otherwise, process read 
			// and write operations with the client
			if (GetOverlappedResult(g_hVideoExcelReportPipeHandle, &Ovlap,&BytesTransferred, TRUE) == 0)
			{
				g_bVideoExcelReportPipeConnected = false;

				TRACE("GetOverlapped result failed %d start over\n", GetLastError());

				if (DisconnectNamedPipe(g_hVideoExcelReportPipeHandle) == 0)
				{
					TRACE("DisconnectNamedPipe failed with error %d\n",GetLastError());
					break;
				}

				if (ConnectNamedPipe(g_hVideoExcelReportPipeHandle,&Ovlap) == 0)
				{
					if (GetLastError() != ERROR_IO_PENDING)
					{
						// Severe error on pipe. Close this handle forever.
						TRACE("ConnectNamedPipe for pipe %d failed with error %d\n", i, GetLastError());
						break;
					}
				}
			} 
			else
			{
				g_bVideoExcelReportPipeConnected = true;

				if (!bReadEvent)//讀
				{
					//收到連接請求或者客戶端數據,重新設置阻塞
					TRACE("Received %d bytes, echo bytes back\n",BytesTransferred);

					if (ReadFile(g_hVideoExcelReportPipeHandle, strReadBuf,VIDOE_EXCEL_REPORT_PIPE_MAX_BUF, NULL, &Ovlap) == 0)
					{
開發者ID:github188,項目名稱:MonitorSystem,代碼行數:67,代碼來源:VideoExcelReportPipeServer.cpp

示例13: w_set_thread_name

static void *readchanges_thread(void *arg) {
  w_root_t *root = arg;
  struct winwatch_root_state *state = root->watch;
  DWORD size = WATCHMAN_BATCH_LIMIT * (sizeof(FILE_NOTIFY_INFORMATION) + 512);
  char *buf;
  DWORD err, filter;
  OVERLAPPED olap;
  BOOL initiate_read = true;
  HANDLE handles[2] = { state->olap, state->ping };
  DWORD bytes;

  w_set_thread_name("readchange %.*s",
      root->root_path->len, root->root_path->buf);

  // Block until winmatch_root_st is waiting for our initialization
  pthread_mutex_lock(&state->mtx);

  filter = FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|
    FILE_NOTIFY_CHANGE_ATTRIBUTES|FILE_NOTIFY_CHANGE_SIZE|
    FILE_NOTIFY_CHANGE_LAST_WRITE;

  memset(&olap, 0, sizeof(olap));
  olap.hEvent = state->olap;

  buf = malloc(size);
  if (!buf) {
    w_log(W_LOG_ERR, "failed to allocate %u bytes for dirchanges buf\n", size);
    goto out;
  }

  if (!ReadDirectoryChangesW(state->dir_handle, buf, size,
        TRUE, filter, NULL, &olap, NULL)) {
    err = GetLastError();
    w_log(W_LOG_ERR,
        "ReadDirectoryChangesW: failed, cancel watch. %s\n",
        win32_strerror(err));
    w_root_lock(root);
    w_root_cancel(root);
    w_root_unlock(root);
    goto out;
  }
  // Signal that we are done with init.  We MUST do this AFTER our first
  // successful ReadDirectoryChangesW, otherwise there is a race condition
  // where we'll miss observing the cookie for a query that comes in
  // after we've crawled but before the watch is established.
  w_log(W_LOG_DBG, "ReadDirectoryChangesW signalling as init done");
  pthread_cond_signal(&state->cond);
  pthread_mutex_unlock(&state->mtx);
  initiate_read = false;

  // The state->mutex must not be held when we enter the loop
  while (!root->cancelled) {
    if (initiate_read) {
      if (!ReadDirectoryChangesW(state->dir_handle,
            buf, size, TRUE, filter, NULL, &olap, NULL)) {
        err = GetLastError();
        w_log(W_LOG_ERR,
            "ReadDirectoryChangesW: failed, cancel watch. %s\n",
            win32_strerror(err));
        w_root_lock(root);
        w_root_cancel(root);
        w_root_unlock(root);
        break;
      } else {
        initiate_read = false;
      }
    }

    w_log(W_LOG_DBG, "waiting for change notifications");
    DWORD status = WaitForMultipleObjects(2, handles, FALSE, INFINITE);

    if (status == WAIT_OBJECT_0) {
      bytes = 0;
      if (!GetOverlappedResult(state->dir_handle, &olap,
            &bytes, FALSE)) {
        err = GetLastError();
        w_log(W_LOG_ERR, "overlapped ReadDirectoryChangesW(%s): 0x%x %s\n",
            root->root_path->buf,
            err, win32_strerror(err));

        if (err == ERROR_INVALID_PARAMETER && size > NETWORK_BUF_SIZE) {
          // May be a network buffer related size issue; the docs say that
          // we can hit this when watching a UNC path. Let's downsize and
          // retry the read just one time
          w_log(W_LOG_ERR, "retrying watch for possible network location %s "
              "with smaller buffer\n", root->root_path->buf);
          size = NETWORK_BUF_SIZE;
          initiate_read = true;
          continue;
        }

        if (err == ERROR_NOTIFY_ENUM_DIR) {
          w_root_schedule_recrawl(root, "ERROR_NOTIFY_ENUM_DIR");
        } else {
          w_log(W_LOG_ERR, "Cancelling watch for %s\n",
              root->root_path->buf);
          w_root_lock(root);
          w_root_cancel(root);
          w_root_unlock(root);
          break;
//.........這裏部分代碼省略.........
開發者ID:CedarLogic,項目名稱:watchman,代碼行數:101,代碼來源:win32.c

示例14: sizeof

bool CCacheDlg::GetStatusFromRemoteCache(const CTGitPath& Path, bool bRecursive)
{
	if(!EnsurePipeOpen())
	{
		STARTUPINFO startup = { 0 };
		PROCESS_INFORMATION process = { 0 };
		startup.cb = sizeof(startup);

		CString sCachePath = L"TGitCache.exe";
		if (CreateProcess(sCachePath.GetBuffer(sCachePath.GetLength() + 1), L"", nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process) == 0)
		{
			// It's not appropriate to do a message box here, because there may be hundreds of calls
			sCachePath.ReleaseBuffer();
			ATLTRACE("Failed to start cache\n");
			return false;
		}
		sCachePath.ReleaseBuffer();

		// Wait for the cache to open
		ULONGLONG endTime = GetTickCount64()+1000;
		while(!EnsurePipeOpen())
		{
			if((GetTickCount64() - endTime) > 0)
			{
				return false;
			}
		}
	}


	DWORD nBytesRead;
	TGITCacheRequest request;
	request.flags = TGITCACHE_FLAGS_NONOTIFICATIONS;
	if(bRecursive)
	{
		request.flags |= TGITCACHE_FLAGS_RECUSIVE_STATUS;
	}
	wcsncpy_s(request.path, Path.GetWinPath(), MAX_PATH);
	SecureZeroMemory(&m_Overlapped, sizeof(OVERLAPPED));
	m_Overlapped.hEvent = m_hEvent;
	// Do the transaction in overlapped mode.
	// That way, if anything happens which might block this call
	// we still can get out of it. We NEVER MUST BLOCK THE SHELL!
	// A blocked shell is a very bad user impression, because users
	// who don't know why it's blocked might find the only solution
	// to such a problem is a reboot and therefore they might loose
	// valuable data.
	// Sure, it would be better to have no situations where the shell
	// even can get blocked, but the timeout of 5 seconds is long enough
	// so that users still recognize that something might be wrong and
	// report back to us so we can investigate further.

	TGITCacheResponse ReturnedStatus;
	BOOL fSuccess = TransactNamedPipe(m_hPipe,
		&request, sizeof(request),
		&ReturnedStatus, sizeof(ReturnedStatus),
		&nBytesRead, &m_Overlapped);

	if (!fSuccess)
	{
		if (GetLastError()!=ERROR_IO_PENDING)
		{
			ClosePipe();
			return false;
		}

		// TransactNamedPipe is working in an overlapped operation.
		// Wait for it to finish
		DWORD dwWait = WaitForSingleObject(m_hEvent, INFINITE);
		if (dwWait == WAIT_OBJECT_0)
		{
			fSuccess = GetOverlappedResult(m_hPipe, &m_Overlapped, &nBytesRead, FALSE);
			return TRUE;
		}
		else
			fSuccess = FALSE;
	}

	ClosePipe();
	return false;
}
開發者ID:stahta01,項目名稱:wxTortoiseGit,代碼行數:81,代碼來源:CacheDlg.cpp

示例15: hid_read

int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
{
	DWORD bytes_read;
	BOOL res;

	HANDLE ev;
	ev = CreateEvent(NULL, FALSE, FALSE /*inital state f=nonsignaled*/, NULL);

	OVERLAPPED ol;
	memset(&ol, 0, sizeof(ol));
	ol.hEvent = ev;

	// Limit the data to be returned. This ensures we get
	// only one report returned per call to hid_read().
	length = (length < dev->input_report_length)? length: dev->input_report_length;

	res = ReadFile(dev->device_handle, data, length, &bytes_read, &ol);
	
	
	if (!res) {
		if (GetLastError() != ERROR_IO_PENDING) {
			// ReadFile() has failed.
			// Clean up and return error.
			CloseHandle(ev);
			goto end_of_function;
		}
	}

	if (!dev->blocking) {
		// See if there is any data yet.
		res = WaitForSingleObject(ev, 0);
		CloseHandle(ev);
		if (res != WAIT_OBJECT_0) {
			// There was no data. Cancel this read and return.
			CancelIo(dev->device_handle);
			// Zero bytes available.
			return 0;
		}
	}

	// Either WaitForSingleObject() told us that ReadFile has completed, or
	// we are in non-blocking mode. Get the number of bytes read. The actual
	// data has been copied to the data[] array which was passed to ReadFile().
	res = GetOverlappedResult(dev->device_handle, &ol, &bytes_read, TRUE/*wait*/);

	if (bytes_read > 0 && data[0] == 0x0) {
		/* If report numbers aren't being used, but Windows sticks a report
		   number (0x0) on the beginning of the report anyway. To make this
		   work like the other platforms, and to make it work more like the
		   HID spec, we'll skip over this byte. */
		bytes_read--;
		memmove(data, data+1, bytes_read);
	}
	
end_of_function:
	if (!res) {
		register_error(dev, "ReadFile");
		return -1;
	}
	
	return bytes_read;
}
開發者ID:mendes-jose,項目名稱:xde-sim,代碼行數:62,代碼來源:hid.cpp


注:本文中的GetOverlappedResult函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。