Esempio n. 1
0
DWORD WINAPI CEgTcpDriver::Stop()
{
	CAutoLock lock(&m_InitLock);

	if (!m_bInited)
		return ERROR_SERVICE_NOT_ACTIVE;

	m_bInited = FALSE;

	WSASetEvent(m_hWsaEvents[WSASHUTDOWN_EVENT]);

	WaitForSingleObject(m_hWSAEventThread, INFINITE);
	CloseHandle(m_hWSAEventThread);

    for (DWORD i = 0; i < m_dwThreadCount; i++)
        PostQueuedCompletionStatus(m_hIocp, 0, 0, NULL);

	HANDLE * ThreadHandles = new HANDLE[m_dwThreadCount];
	for (i = 0; i < m_dwThreadCount; i++)
		ThreadHandles[i] = m_hThreads[i];

	WaitForMultipleObjects(m_dwThreadCount,  ThreadHandles, TRUE, INFINITE);

	delete [] ThreadHandles;
	for (i = 0; i < m_dwThreadCount; i++)
		CloseHandle(m_hThreads[i]);
	
	m_hThreads.clear();

	if (m_usServerPort != CLIENT_ONLY)
	{
		closesocket(m_ListenSocket);                                
		closesocket(m_ListenSocketContext.m_pIOContext.m_SocketAccept);

		while (!HasOverlappedIoCompleted((LPOVERLAPPED)&m_ListenSocketContext.m_pIOContext.m_SendOverlapped)) 
		   Sleep(0);

		while (!HasOverlappedIoCompleted((LPOVERLAPPED)&m_ListenSocketContext.m_pIOContext.m_ReceiveOverlapped)) 
		   Sleep(0);
	}

	CloseHandle(m_hIocp);

	for(i = 0; i < WSATOTAL_EVENTS; i++)
		WSACloseEvent(m_hWsaEvents[i]);

	for(set<PER_SOCKET_CONTEXT>::iterator
		it = m_SocketContexts.begin(); 
		it != m_SocketContexts.end();
		)
	{
		set<PER_SOCKET_CONTEXT>::iterator DelIt = it;
		it++;
		CloseClient(*DelIt);
	}

	return 0;
}
Esempio n. 2
0
/// Stops monitoring a directory.
void DestroyWatch(WatchStruct* pWatch)
{
	if(!pWatch) return;

	pWatch->mStopNow = TRUE;

	// Cancels all pending input and output (I/O) operations
	// that are issued by the calling thread for the specified file.
	// The function does not cancel I/O operations that other threads issue for a file handle.
	// If the function succeeds, the return value is nonzero. 
	//
	//const BOOL bCancelIoResult = CancelIo(pWatch->mDirHandle);
	//(void)bCancelIoResult;

	RefreshWatch(pWatch, true);

	if (!HasOverlappedIoCompleted(&pWatch->mOverlapped))
	{
		SleepEx(5, TRUE);
	}

	CloseHandle(pWatch->mOverlapped.hEvent);
	CloseHandle(pWatch->mDirHandle);

	HeapFree(GetProcessHeap(), 0, pWatch);

	Assert(numWatches > 0);
	--numWatches;
}
Esempio n. 3
0
BOOL CALLBACK CCircuitry::OnRecMemBlockDone(int ch, int nEndReason, PUCHAR pucBuf, DWORD dwStopOffset, PVOID pV)
{
	enum {
		RecordBy_BlockApp	= 1,
		RecordBy_RcvDtmf	= 2,
		RecordBy_Hangup		= 3,
		RecordBy_Done		= 4,
	};
	
	if ( SsmGetChState(ch) == S_CALL_STANDBY ) nEndReason = RecordBy_Hangup;
	
	OVERLAPPED*	pRecIoOver = (OVERLAPPED*)pV;
//TRACE("%i-> OnRecMemBlockDone in [%i]\n", GetTickCount(), pRecIoOver->Offset);
	
	CSingleLock pLock( &Neighbour.m_pSection );
	for ( ; HasOverlappedIoCompleted(pRecIoOver) && ! pLock.Lock(50); );
	
	if ( ! --pRecIoOver->Offset ) SetEvent( pRecIoOver->hEvent );
	
	CCircuitry* pChannel = (CCircuitry*) pRecIoOver->InternalHigh;
	
	if ( nEndReason == RecordBy_Done && pLock.IsLocked() )
	{
		pChannel->RecordWith( ch, pucBuf, min(dwStopOffset,TEMP_BUFFER) );
	}
	else if ( nEndReason != RecordBy_Done )
	{
		pRecIoOver->OffsetHigh = -1;
		if ( nEndReason == RecordBy_Hangup ) pChannel->m_nTaskId = -1;
	}
	
	return TRUE;
}
Esempio n. 4
0
BOOL CALLBACK CCircuitry::OnPlayMemBlockDone(int ch, int nEndReason, PUCHAR pucBuf, DWORD dwStopOffset, PVOID pV)
{
	enum {
		PlayBy_Done		= 1,
		PlayBy_RcvDtmf	= 2,
		PlayBy_RcvBargein=3,
		PlayBy_Hangup	= 4,
		PlayBy_BlockApp	= 5,
	};
	
	if ( SsmGetChState(ch) == S_CALL_STANDBY ) nEndReason = PlayBy_Hangup;
	
	OVERLAPPED*	pPlayIoOver = (OVERLAPPED*)pV;
//TRACE("%i-> OnPlayMemBlockDone[%i] in [%i]\n", GetTickCount(), nEndReason,pPlayIoOver->Offset);
	
	CSingleLock pLock( &Neighbour.m_pSection );
	for ( ; HasOverlappedIoCompleted(pPlayIoOver) && ! pLock.Lock(50); );
	
	if ( ! --pPlayIoOver->Offset ) SetEvent( pPlayIoOver->hEvent );
	
	CCircuitry* pChannel = (CCircuitry*) pPlayIoOver->InternalHigh;
	
	if ( nEndReason == PlayBy_Done && pLock.IsLocked() )
	{
		pChannel->ReplayWith( ch, pChannel->m_pChain );
	}
	else if ( nEndReason != PlayBy_Done )
	{
		pPlayIoOver->OffsetHigh = -1;
		if ( nEndReason == PlayBy_Hangup ) pChannel->m_nTaskId = -1;
	}
	
	return TRUE;
}
Esempio n. 5
0
static void eof_timer_cb(uv_timer_t* timer, int status) {
  uv_pipe_t* pipe = (uv_pipe_t*) timer->data;
  uv_loop_t* loop = timer->loop;

  assert(status == 0); /* timers can't fail */
  assert(pipe->type == UV_NAMED_PIPE);

  /* This should always be true, since we start the timer only */
  /* in uv_pipe_queue_read after successfully calling ReadFile, */
  /* or in uv_process_pipe_shutdown_req if a read is pending, */
  /* and we always immediately stop the timer in */
  /* uv_process_pipe_read_req. */
  assert(pipe->flags & UV_HANDLE_READ_PENDING);

  /* If there are many packets coming off the iocp then the timer callback */
  /* may be called before the read request is coming off the queue. */
  /* Therefore we check here if the read request has completed but will */
  /* be processed later. */
  if ((pipe->flags & UV_HANDLE_READ_PENDING) &&
      HasOverlappedIoCompleted(&pipe->read_req.overlapped)) {
    return;
  }

  /* Force both ends off the pipe. */
  CloseHandle(pipe->handle);
  pipe->handle = INVALID_HANDLE_VALUE;

  /* Stop reading, so the pending read that is going to fail will */
  /* not be reported to the user. */
  uv_read_stop((uv_stream_t*) pipe);

  /* Report the eof and update flags. This will get reported even if the */
  /* user stopped reading in the meantime. TODO: is that okay? */
  uv_pipe_read_eof(loop, pipe, uv_null_buf_);
}
Esempio n. 6
0
int CCircuitry::RecordWith(int nChan, BYTE* pBuffer, DWORD dwStopOffset)
{
	if ( ! m_pChain || ! m_pChain->IsConnected() ) return -1;
	
	if ( m_pRecIoOver->Offset >= MAX_RECLST ) return -1;
	if ( ! HasOverlappedIoCompleted(m_pRecIoOver) ) return -1;
	
	CBuffer* pOutput = m_pChain->m_pOutput;
	if ( dwStopOffset ) pOutput->Add( pBuffer, dwStopOffset + 1 );
	
	Neighbour.m_pWakeup.SetEvent();
	
	if ( int nResult = SsmRecordMemBlock(nChan, 6, pBuffer, TEMP_BUFFER, OnRecMemBlockDone, m_pRecIoOver) )
	{
#ifdef _DEBUG
		CHAR sError[1024];
		SsmGetLastErrMsg( sError );
		theApp.Message( MSG_ERROR, sError );
#endif
		return nResult;
	}
	
	m_pRecIoOver->Offset++;
	ResetEvent( m_pRecIoOver->hEvent );
	
//TRACE("%i-> RecordWith in [%i]\n", GetTickCount(), m_pRecIoOver->Offset);
	return 0;
}
Esempio n. 7
0
// pb with this code: works if no receiving of chars has been previously done
static int gry_check(CableHandle *h, int *status)
{
	BOOL fSuccess;
	static DWORD dwEvtMask = 0;
	static OVERLAPPED ol = { 0 };

	static BOOL iop;
	static BOOL ioPending = FALSE;

	if (ioPending == FALSE)
	{
		memset(&ol, 0, sizeof(OVERLAPPED));
		fSuccess = WaitCommEvent(hCom, &dwEvtMask, &ol);

		ioPending = TRUE;
		printf("$ (%i)\n", ioPending);
	}
	else
	{
		if (HasOverlappedIoCompleted(&ol))
		{
			if (dwEvtMask & EV_RXCHAR)
			{
				*status = STATUS_RX;
				printf("#\n");
				ioPending = FALSE;
			}
		}
	}

	return 0;
}
Esempio n. 8
0
static int gry_get(CableHandle* h, uint8_t *data, uint32_t len)
{
	BOOL fSuccess;
	DWORD nBytesRead;
	OVERLAPPED ol;
	uint32_t i;

	for(i = 0; i < len;)
	{
		memset(&ol, 0, sizeof(OVERLAPPED));
		fSuccess = ReadFile(hCom, data + i, len - i, &nBytesRead, &ol);

		while(HasOverlappedIoCompleted(&ol) == FALSE) Sleep(0);
		fSuccess = GetOverlappedResult(hCom, &ol, &nBytesRead, FALSE);

		if (!fSuccess) 
		{
			ticables_warning("ReadFile");
			return ERR_READ_ERROR;
		}
		else if (nBytesRead == 0) 
		{
			ticables_warning("ReadFile");
			return ERR_READ_TIMEOUT;
		}

		i += nBytesRead;
	}
	printf("get : %i %i %i\n", fSuccess, nBytesRead, len);

	return 0;
}
Esempio n. 9
0
static int gry_put(CableHandle* h, uint8_t *data, uint32_t len)
{
	BOOL fSuccess;
	DWORD nBytesWritten;
	OVERLAPPED ol;

	memset(&ol, 0, sizeof(OVERLAPPED));
	fSuccess = WriteFile(hCom, data, len, &nBytesWritten, &ol);

	while(HasOverlappedIoCompleted(&ol) == FALSE) Sleep(0);

	fSuccess = GetOverlappedResult(hCom, &ol, &nBytesWritten, FALSE);
	if (!fSuccess) 
	{
		ticables_warning("WriteFile");
		return ERR_WRITE_ERROR;
	}
	else if (nBytesWritten == 0) 
	{
		ticables_warning("WriteFile");
		return ERR_WRITE_TIMEOUT;
	}
	else if (nBytesWritten < len)
	{
		ticables_warning("WriteFile");
		return ERR_WRITE_ERROR;
	}

	return 0;
}
Esempio n. 10
0
int RCX_receive(unsigned char *rcbuf, unsigned long length){
  //attempts to read a message of specified length from the RCX
  unsigned long res=0;
  int i;

  ovl.Offset=0;
  ovl.OffsetHigh=0;
  ovl.hEvent=NULL;
  if (!ReadFile(RCX_port,rcbuf,length,&res,&ovl)){
    //return(0);
    if (GetLastError()==ERROR_IO_PENDING){
      i=0;
      do{
        Sleep(10);
        i++;
      } while ((!HasOverlappedIoCompleted(&ovl))&&(i<50));
      if (i<50){
        GetOverlappedResult(RCX_port,&ovl,&res,FALSE);
        return(res); //completed.
      } else {
        CancelIo(RCX_port); //cancel transmission.
        return(0); //not completed.
      }
    } else { //some error occured
      CancelIo(RCX_port); //cancel transmission.
      return(0);
    }
  }
  return(res);
}
Esempio n. 11
0
bool File::HasAsyncIOCompleted()
{
#if _WIN32 || _WIN64
	return HasOverlappedIoCompleted( &m_overlapped );
#else
	return false;
#endif
}
Esempio n. 12
0
void 
USBDevice_internalFlush(LPSKYETEK_DEVICE device, BOOL lockSendBuffer)
{
	#ifndef WINCE
	OVERLAPPED overlap;
	#else
	COMMTIMEOUTS ctos;
	DEVICEIMPL* pImpl;
	#endif
	unsigned char sendBuffer[65];
	LPUSB_DEVICE usbDevice;
	unsigned int bytesWritten;
	
	if(device == NULL)
		return;

	usbDevice = (LPUSB_DEVICE)device->user;

	if(lockSendBuffer)
		EnterCriticalSection(&usbDevice->sendBufferMutex);

	if(usbDevice->sendBufferWritePtr == usbDevice->sendBuffer)
		goto end;

	/* Windows HID command */
	sendBuffer[0] = 0;
	/* Actual length of data */
	sendBuffer[1] = (usbDevice->sendBufferWritePtr - usbDevice->sendBuffer);
	CopyMemory((sendBuffer + 2), usbDevice->sendBuffer, sendBuffer[1]);

	bytesWritten = 0;
	
#ifndef WINCE
	ZeroMemory(&overlap, sizeof(OVERLAPPED));
	overlap.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	
	WriteFile(device->writeFD, sendBuffer, 65, &bytesWritten, &overlap);
	
	WaitForSingleObject(overlap.hEvent, 100);

	CloseHandle(overlap.hEvent);
	
	if(!HasOverlappedIoCompleted(&overlap))
		CancelIo(device->writeFD);
#else
	pImpl = (DEVICEIMPL*)device->internal;
	ZeroMemory(&ctos,sizeof(COMMTIMEOUTS));
	ctos.WriteTotalTimeoutConstant = pImpl->timeout;
	SetCommTimeouts(device->writeFD, &ctos);
	WriteFile(device->writeFD, sendBuffer, 65, &bytesWritten, NULL);
#endif
	
	usbDevice->sendBufferWritePtr = usbDevice->sendBuffer;

end:
	if(lockSendBuffer)
		LeaveCriticalSection(&usbDevice->sendBufferMutex);
}
bool AdbIOCompletion::IsCompleted() {
  SetLastError(NO_ERROR);
  if (!IsOpened()) {
    SetLastError(ERROR_INVALID_HANDLE);
    return true;
  }

  return  HasOverlappedIoCompleted(overlapped()) ? true : false;
}
Esempio n. 14
0
static int wince_handle_events(
	struct libusb_context *ctx,
	struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
{
	struct wince_transfer_priv* transfer_priv = NULL;
	POLL_NFDS_TYPE i = 0;
	BOOL found = FALSE;
	struct usbi_transfer *transfer;
	DWORD io_size, io_result;
	int r = LIBUSB_SUCCESS;

	usbi_mutex_lock(&ctx->open_devs_lock);
	for (i = 0; i < nfds && num_ready > 0; i++) {

		usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);

		if (!fds[i].revents)
			continue;

		num_ready--;

		// Because a Windows OVERLAPPED is used for poll emulation,
		// a pollable fd is created and stored with each transfer
		usbi_mutex_lock(&ctx->flying_transfers_lock);
		list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
			transfer_priv = usbi_transfer_get_os_priv(transfer);
			if (transfer_priv->pollable_fd.fd == fds[i].fd) {
				found = TRUE;
				break;
			}
		}
		usbi_mutex_unlock(&ctx->flying_transfers_lock);

		if (found && HasOverlappedIoCompleted(transfer_priv->pollable_fd.overlapped)) {
			io_result = (DWORD)transfer_priv->pollable_fd.overlapped->Internal;
			io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
			usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
			// let handle_callback free the event using the transfer wfd
			// If you don't use the transfer wfd, you run a risk of trying to free a
			// newly allocated wfd that took the place of the one from the transfer.
			wince_handle_callback(transfer, io_result, io_size);
		} else if (found) {
			usbi_err(ctx, "matching transfer for fd %d has not completed", fds[i]);
			r = LIBUSB_ERROR_OTHER;
			break;
		} else {
			usbi_err(ctx, "could not find a matching transfer for fd %d", fds[i]);
			r = LIBUSB_ERROR_NOT_FOUND;
			break;
		}
	}
	usbi_mutex_unlock(&ctx->open_devs_lock);

	return r;
}
Esempio n. 15
0
BOOL STDCALL OSFileHasChanged (OSFileChangeData *data)
{
    BOOL hasModified = FALSE;

    if(HasOverlappedIoCompleted(&data->directoryChange))
    {
        FILE_NOTIFY_INFORMATION *notify = (FILE_NOTIFY_INFORMATION*)data->changeBuffer;

        for (;;)
        {
            if (notify->Action != FILE_ACTION_RENAMED_OLD_NAME && notify->Action != FILE_ACTION_REMOVED)
            {
                String strFileName;
                strFileName.SetLength(notify->FileNameLength);
                scpy_n(strFileName, notify->FileName, notify->FileNameLength/2);
                strFileName.KillSpaces();

                String strFileChanged;
                strFileChanged << data->strDirectory << strFileName;             

                if(strFileChanged.CompareI(data->targetFileName))
                {
                    hasModified = TRUE;
                    break;
                }
            }

            if (!notify->NextEntryOffset)
                break;

            notify = (FILE_NOTIFY_INFORMATION*)((BYTE *)notify + notify->NextEntryOffset);
        }

        CloseHandle (data->directoryChange.hEvent);

        DWORD test;
        zero(&data->directoryChange, sizeof(data->directoryChange));
        zero(data->changeBuffer, sizeof(data->changeBuffer));

        data->directoryChange.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);

        if(ReadDirectoryChangesW(data->hDirectory, data->changeBuffer, 2048, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE, &test, &data->directoryChange, NULL))
        {
        }
        else
        {
            CloseHandle(data->directoryChange.hEvent);
            CloseHandle(data->hDirectory);
            return hasModified;
        }
    }

    return hasModified;
}
Esempio n. 16
0
BOOL CNeighbour::AcceptCircuitry()
{
	if ( m_hPipe == INVALID_HANDLE_VALUE ) return Connect( Settings.Centric.Local );
	if ( ! HasOverlappedIoCompleted( &m_pOverlapped ) ) return TRUE;
	
	SetChannel( new CCircuitry( m_hPipe ) );
	
	m_hPipe	= INVALID_HANDLE_VALUE;
	
	return TRUE;
}
Esempio n. 17
0
VOID STDCALL OSMonitorFileDestroy (OSFileChangeData *data)
{
    if(!HasOverlappedIoCompleted(&data->directoryChange))
    {
        CancelIoEx(data->hDirectory, &data->directoryChange);
        WaitForSingleObject(data->directoryChange.hEvent, INFINITE);
    }

    CloseHandle(data->directoryChange.hEvent);
    CloseHandle(data->hDirectory);
    Free(data);
}
Esempio n. 18
0
static void win32_aio_cancel(BlockDriverAIOCB *blockacb)
{
    QEMUWin32AIOCB *waiocb = (QEMUWin32AIOCB *)blockacb;

    /*
     * CancelIoEx is only supported in Vista and newer.  For now, just
     * wait for completion.
     */
    while (!HasOverlappedIoCompleted(&waiocb->ov)) {
        aio_poll(bdrv_get_aio_context(blockacb->bs), true);
    }
}
int TFileAioWriter::write(const char *data, int length)
{
    QMutexLocker locker(&d->mutex);

    if (!isOpen()) {
        return -1;
    }

    // check whether last writing is finished
    if (d->syncBuffer.count() > 0) {
        aiobuf_t *lastab = d->syncBuffer.last();
        if (HasOverlappedIoCompleted(&lastab->aio_overlap)) {
            d->clearSyncBuffer();
        }
    }

    if (length <= 0)
        return -1;

    int len = length;
    if (data[length - 1] == '\n') {
        ++len;
    }

    aiobuf_t *ab = new aiobuf_t;
    memset(ab, 0, sizeof(aiobuf_t));

    ab->aio_nbytes = len;
    ab->aio_buf = new char[len];
    ab->aio_overlap.Offset = 0xFFFFFFFF;
    ab->aio_overlap.OffsetHigh = 0xFFFFFFFF;
    memcpy((void *)ab->aio_buf, data, length);

    // the last char only LF -> CRLF
    if (len != length) {
        ab->aio_buf[len - 2] = '\r';
        ab->aio_buf[len - 1] = '\n';
    }

    WriteFile(d->fileHandle, ab->aio_buf, (DWORD)len, NULL, &ab->aio_overlap);
    if (GetLastError() != ERROR_IO_PENDING) {
        //fprintf(stderr, "WriteFile error str: %s\n", data);
        delete (char *)ab->aio_buf;
        delete ab;

        close();
        return -1;
    }

    d->syncBuffer << ab;
    return 0;
}
Esempio n. 20
0
FileMon::~FileMon() {
#ifdef WIN32
  for(auto i : mWatches) {
    WatchStruct* pWatch=i.second;

    DWORD dwWaitResult = WaitForSingleObject(ghMutex,INFINITE);

    while(true) {
      if(dwWaitResult==WAIT_OBJECT_0) {
        pWatch->mStopNow = TRUE;

        if(!ReleaseMutex(ghMutex)) {
          std::cout << "FileMon : Release mutex err.\n";
        }

        break;
      } else if(dwWaitResult==WAIT_ABANDONED) {
        break;
      }
    }

    CancelIo(pWatch->mDirHandle);

    ReadDirectoryChangesW(
      pWatch->mDirHandle,pWatch->mBuffer,sizeof(pWatch->mBuffer),FALSE,
      pWatch->mNotifyFilter,NULL,&pWatch->mOverlapped,0);

    if(!HasOverlappedIoCompleted(&pWatch->mOverlapped)) {
      SleepEx(5,TRUE);
    }

    CloseHandle(pWatch->mOverlapped.hEvent);
    CloseHandle(pWatch->mDirHandle);
    HeapFree(GetProcessHeap(),0,pWatch);
  }

  CloseHandle(ghMutex);
#endif

#ifdef LINUX
  if(notify) {
    for(auto i : watchMap) {
      inotify_rm_watch(notify,i.first); //unnecessary because of close below?
    }
  }

  if(notify) {
    close(notify);
  }
#endif
}
Esempio n. 21
0
int CSerialController::readNonblock(unsigned char* buffer, unsigned int length)
{
	assert(m_handle != INVALID_HANDLE_VALUE);
	assert(buffer != NULL);

	if (length > BUFFER_LENGTH)
		length = BUFFER_LENGTH;

	if (m_readPending && length != m_readLength) {
		::CancelIo(m_handle);
		m_readPending = false;
	}

	m_readLength = length;

	if (length == 0U)
		return 0;

	if (!m_readPending) {
		DWORD bytes = 0UL;
		BOOL res = ::ReadFile(m_handle, m_readBuffer, m_readLength, &bytes, &m_readOverlapped);
		if (res) {
			::memcpy(buffer, m_readBuffer, bytes);
			return int(bytes);
		}

		DWORD error = ::GetLastError();
		if (error != ERROR_IO_PENDING) {
			::fprintf(stderr, "Error from ReadFile: %04lx\n", error);
			return -1;
		}

		m_readPending = true;
	}

	BOOL res = HasOverlappedIoCompleted(&m_readOverlapped);
	if (!res)
		return 0;

	DWORD bytes = 0UL;
	res = ::GetOverlappedResult(m_handle, &m_readOverlapped, &bytes, TRUE);
	if (!res) {
		::fprintf(stderr, "Error from GetOverlappedResult (ReadFile): %04lx\n", ::GetLastError());
		return -1;
	}

	::memcpy(buffer, m_readBuffer, bytes);
	m_readPending = false;

	return int(bytes);
}
Esempio n. 22
0
void FileWatcherWin32::run()
{
	if ( mHandles.empty() )
	{
		return;
	}

	do
	{
		if ( !mHandles.empty() )
		{
			mWatchesLock.lock();

			for ( std::size_t i = 0; i < mWatches.size(); i++ )
			{
				WatcherStructWin32 * watch = mWatches[ i ];

				// If the overlapped struct was cancelled ( because the creator thread doesn't exists anymore ),
				// we recreate the overlapped in the current thread and refresh the watch
				if ( /*STATUS_CANCELED*/0xC0000120 == watch->Overlapped.Internal )
				{
					watch->Overlapped = OVERLAPPED();
					RefreshWatch(watch);
				}

				// First ensure that the handle is the same, this means that the watch was not removed.
				if ( HasOverlappedIoCompleted( &watch->Overlapped ) && mHandles[ i ] == watch->Watch->DirHandle )
				{
					DWORD bytes;

					if ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) )
					{
						WatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped );
					}
				}
			}

			mWatchesLock.unlock();

			if ( mInitOK )
			{
				System::sleep( 10 );
			}
		}
		else
		{
			// Wait for a new handle to be added
			System::sleep( 10 );
		}
	} while ( mInitOK );
}
Esempio n. 23
0
static void
Overlapped_dealloc(OverlappedObject *self)
{
    DWORD bytes;
    DWORD olderr = GetLastError();
    BOOL wait = FALSE;
    BOOL ret;

    if (!HasOverlappedIoCompleted(&self->overlapped) &&
        self->type != TYPE_NOT_STARTED)
    {
        if (Py_CancelIoEx && Py_CancelIoEx(self->handle, &self->overlapped))
            wait = TRUE;

        Py_BEGIN_ALLOW_THREADS
        ret = GetOverlappedResult(self->handle, &self->overlapped,
                                  &bytes, wait);
        Py_END_ALLOW_THREADS

        switch (ret ? ERROR_SUCCESS : GetLastError()) {
            case ERROR_SUCCESS:
            case ERROR_NOT_FOUND:
            case ERROR_OPERATION_ABORTED:
                break;
            default:
                PyErr_Format(
                    PyExc_RuntimeError,
                    "%R still has pending operation at "
                    "deallocation, the process may crash", self);
                PyErr_WriteUnraisable(NULL);
        }
    }

    if (self->overlapped.hEvent != NULL)
        CloseHandle(self->overlapped.hEvent);

    switch (self->type) {
    case TYPE_READ:
    case TYPE_ACCEPT:
        Py_CLEAR(self->allocated_buffer);
        break;
    case TYPE_WRITE:
    case TYPE_READINTO:
        if (self->user_buffer.obj)
            PyBuffer_Release(&self->user_buffer);
        break;
    }
    PyObject_Del(self);
    SetLastError(olderr);
}
Esempio n. 24
0
    ~WatchInfo()
    {
        if(m_handle != INVALID_HANDLE_VALUE) {

            m_isStopping = true;
            ::CancelIo(m_handle);
            registerCompletionRoutine(false);

            if(!HasOverlappedIoCompleted(&m_overlapped)) {
                ::SleepEx(1, TRUE);
            }

            ::CloseHandle(m_overlapped.hEvent);
            ::CloseHandle(m_handle);
        }
    }
Esempio n. 25
0
	void win32_directory_monitor_destroy_record(DirectoryMonitorRecord* record)
	{
		// This is invoked because it forces all completion notifications
		// to happen one last time.
		CancelIo(record->handle);

		// Wait for i/o operations to finish up.
		if (!HasOverlappedIoCompleted(&record->async_data))
		{
			SleepEx(5, TRUE);
		}

		MEMORY2_DEALLOC(_monitor_state->allocator, record->buffer);
		CloseHandle(record->handle);
		MEMORY2_DELETE(_monitor_state->allocator, record);
	}
Esempio n. 26
0
static PyObject *
Overlapped_cancel(OverlappedObject *self)
{
    BOOL ret = TRUE;

    if (self->type == TYPE_NOT_STARTED
        || self->type == TYPE_WAIT_NAMED_PIPE_AND_CONNECT)
        Py_RETURN_NONE;

    if (!HasOverlappedIoCompleted(&self->overlapped)) {
        Py_BEGIN_ALLOW_THREADS
        if (Py_CancelIoEx)
            ret = Py_CancelIoEx(self->handle, &self->overlapped);
        else
            ret = CancelIo(self->handle);
        Py_END_ALLOW_THREADS
    }
Esempio n. 27
0
////////////////////////////////////////////////////////////////////////////////
// 
// FUNCTION:	CIOCPServer::RemoveStaleClient
// 
// DESCRIPTION:	Client has died on us, close socket and remove context from our list
// 
// INPUTS:		
// 
// NOTES:	
// 
// MODIFICATIONS:
// 
// Name                  Date       Version    Comments
// N T ALMOND            06042001	1.0        Origin
// 
////////////////////////////////////////////////////////////////////////////////
void CIOCPServer::RemoveStaleClient(ClientContext* pContext, BOOL bGraceful)
{
    CLock cs(m_cs, "RemoveStaleClient");

	TRACE("CIOCPServer::RemoveStaleClient\n");

    LINGER lingerStruct;


    //
    // If we're supposed to abort the connection, set the linger value
    // on the socket to 0.
    //

    if ( !bGraceful ) 
	{

        lingerStruct.l_onoff = 1;
        lingerStruct.l_linger = 0;
        setsockopt( pContext->m_Socket, SOL_SOCKET, SO_LINGER,
                    (char *)&lingerStruct, sizeof(lingerStruct) );
    }



    //
    // Free context structures
	if (m_listContexts.Find(pContext)) 
	{

		//
		// Now close the socket handle.  This will do an abortive or  graceful close, as requested.  
		CancelIo((HANDLE) pContext->m_Socket);
		closesocket( pContext->m_Socket );

		pContext->m_Socket = INVALID_SOCKET;

        while (!HasOverlappedIoCompleted((LPOVERLAPPED)pContext)) 
                Sleep(0);

		m_pNotifyProc((LPVOID) m_pFrame, pContext, NC_CLIENT_DISCONNECT);

		MoveToFreePool(pContext);

	}
}
Esempio n. 28
0
int RCX_send(unsigned char *message, int length){
  //sends a message to the RCX
  //returns 1 if write succeeded, 0 if failed
  //maximal length of message is 125 bytes
  int i;
  unsigned long res,ptr;
  int s=0;

  //create message to send
  sendbuf[0]=0x55;
  sendbuf[1]=0xff;
  sendbuf[2]=0x00;
  ptr=3;
  for (i=0; i<length; i++){
    sendbuf[ptr++]=message[i];
    sendbuf[ptr++]=message[i]^0xff;
    s+=message[i];
  }
  sendbuf[ptr++]=(unsigned char)s;
  sendbuf[ptr++]=((unsigned char)s)^0xff;

  res=0;
  ovl.Offset=0;
  ovl.OffsetHigh=0;
  ovl.hEvent=NULL;
  if(!WriteFile(RCX_port,sendbuf,ptr,&res,&ovl)){
    if (GetLastError()==ERROR_IO_PENDING){
      i=0;
      do{
        Sleep(10);
        i++;
      } while ((!HasOverlappedIoCompleted(&ovl))&&(i<50));
      if (i<50){
        return(1); //completed.
      } else {
        CancelIo(RCX_port); //cancel transmission.
        return(0); //not completed.
      }
    } else { //some error occured
      CancelIo(RCX_port); //cancel transmission.
      return(0);
    }
  }
  return(1);
}
Esempio n. 29
0
static bool CheckPipeConnection(HANDLE hPipe, HANDLE hEvent, OVERLAPPED *pOl, bool *pbWait)
{
	if (!*pbWait) {
		::ZeroMemory(pOl, sizeof(OVERLAPPED));
		pOl->hEvent = hEvent;
		if (!::ConnectNamedPipe(hPipe, pOl)) {
			// すでに接続されている可能性もある
			DWORD dwErr = ::GetLastError();
			if (dwErr == ERROR_IO_PENDING) *pbWait = true;
			else if (dwErr == ERROR_PIPE_CONNECTED) return true;
		}
	}
	if (*pbWait && HasOverlappedIoCompleted(pOl)) {
		*pbWait = false;
		return true;
	}
	return false;
}
Esempio n. 30
0
void native_dirmonitor_remove(Ref *r)
{
    FileMonitor *fm = Value_ptr(r->v[INDEX_FILEMONITOR_STRUCT]);

    if (fm != NULL) {
        fm->valid = FALSE;
        CancelIo(fm->hDir);
        refresh_dirmonitor(fm, TRUE);

        if (!HasOverlappedIoCompleted(&fm->overlapped)) {
            SleepEx(5, TRUE);
        }
        CloseHandle(fm->hDir);
        CloseHandle(fm->overlapped.hEvent);

        FileMonitor_del(fm);
        r->v[INDEX_FILEMONITOR_STRUCT] = VALUE_NULL;
    }
}