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

C++ GetOverlappedResult函数代码示例

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

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



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


示例16: serial_loop

void serial_loop()
{
    char buff[SERIAL_BUFFER];
    int pos = 0;
#ifdef __WIN32__
    DWORD state, len_in = 0;
    BOOL fWaitingOnRead = FALSE;
    OVERLAPPED osReader = {0};
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if(osReader.hEvent == NULL)
    {
        server_log(LOG_ERR, "serial_loop: CreateEvent");
        exit(EXIT_FAILURE);
    }
    while(1)
    {
        if(!fWaitingOnRead)
        {
            if(!ReadFile(server.serialfd, &buff[pos], 1, &len_in, &osReader))
            {
                if(GetLastError() != ERROR_IO_PENDING)
                {
                    CloseHandle(osReader.hEvent);
                    break;
                }
                else
                    fWaitingOnRead = TRUE;
            }
        }
        if(fWaitingOnRead)
        {
            state = WaitForSingleObject(osReader.hEvent, 200);
            if(state == WAIT_TIMEOUT)
                continue;
            if(state != WAIT_OBJECT_0 ||
               !GetOverlappedResult(server.serialfd, &osReader, &len_in, FALSE))
            {
                CloseHandle(osReader.hEvent);
                break;
            }
            fWaitingOnRead = FALSE;
        }
        if(len_in != 1)
            continue;
#else
    fd_set input;
    FD_ZERO(&input);
    FD_SET(server.serialfd, &input);
    while(select(server.serialfd+1, &input, NULL, NULL, NULL) > 0)
    {
        if(read(server.serialfd, &buff[pos], 1) <= 0)
            break;
#endif
        if(buff[pos] != '\n') /* If this command is too long to fit into a buffer, clip it */
        {
            if(pos != SERIAL_BUFFER-1)
                pos++;
            continue;
        }
        buff[pos] = 0;
        if(pos)
            msg_parse_serial(buff[0], buff+1);
        buff[pos] = '\n';
        msg_send(buff, pos+1);
        pos = 0;
    }
#ifdef __WIN32__
    CloseHandle(server.serialfd);
#else
    close(server.serialfd);
#endif
}

void serial_write(char* msg, int len)
{
    pthread_mutex_lock(&server.mutex_s);
#ifdef __WIN32__
    OVERLAPPED osWrite = {0};
    DWORD dwWritten;

    osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if(osWrite.hEvent == NULL)
    {
        server_log(LOG_ERR, "server_conn: CreateEvent");
        exit(EXIT_FAILURE);
    }

    if(!WriteFile(server.serialfd, msg, len, &dwWritten, &osWrite))
        if(GetLastError() == ERROR_IO_PENDING)
            if(WaitForSingleObject(osWrite.hEvent, INFINITE) == WAIT_OBJECT_0)
                GetOverlappedResult(server.serialfd, &osWrite, &dwWritten, FALSE);
    CloseHandle(osWrite.hEvent);
#else
    write(server.serialfd, msg, len);
#endif
    pthread_mutex_unlock(&server.mutex_s);
}
开发者ID:kkonradpl,项目名称:xdrd,代码行数:97,代码来源:xdrd.c


示例17: EIO_WatchPort

void EIO_WatchPort(uv_work_t* req) {
  WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
  data->bytesRead = 0;
  data->disconnected = false;

  // Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout
  // Event MUST be used if program has several simultaneous asynchronous operations
  // on the same handle (i.e. ReadFile and WriteFile)
  HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

  while (true) {
    OVERLAPPED ov = {0};
    ov.hEvent = hEvent;

    // Start read operation - synchrounous or asynchronous
    DWORD bytesReadSync = 0;
    if (!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {
      data->errorCode = GetLastError();
      if (data->errorCode != ERROR_IO_PENDING) {
        // Read operation error
        if (data->errorCode == ERROR_OPERATION_ABORTED) {
          data->disconnected = true;
        } else {
          ErrorCodeToString("Reading from COM port (ReadFile)", data->errorCode, data->errorString);
          CloseHandle(hEvent);
          return;
        }
        break;
      }

      // Read operation is asynchronous and is pending
      // We MUST wait for operation completion before deallocation of OVERLAPPED struct
      // or read data buffer

      // Wait for async read operation completion or timeout
      DWORD bytesReadAsync = 0;
      if (!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {
        // Read operation error
        data->errorCode = GetLastError();
        if (data->errorCode == ERROR_OPERATION_ABORTED) {
          data->disconnected = true;
        } else {
          ErrorCodeToString("Reading from COM port (GetOverlappedResult)", data->errorCode, data->errorString);
          CloseHandle(hEvent);
          return;
        }
        break;
      } els 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ GetOwner函数代码示例发布时间:2022-05-30
下一篇:
C++ GetOuter函数代码示例发布时间: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