示例#1
0
void TcpConnection::stop() {
  assert(dispatcher != nullptr);
  assert(!stopped);
  if (readContext != nullptr) {
    TcpConnectionContext* context = static_cast<TcpConnectionContext*>(readContext);
    if (!context->interrupted) {
      if (CancelIoEx(reinterpret_cast<HANDLE>(connection), context) != TRUE) {
        DWORD lastError = GetLastError();
        if (lastError != ERROR_NOT_FOUND) {
          throw std::runtime_error("TcpConnection::stop, CancelIoEx failed, result=" + std::to_string(GetLastError()));
        }
      }

      context->interrupted = true;
    }
  }

  if (writeContext != nullptr) {
    TcpConnectionContext* context = static_cast<TcpConnectionContext*>(writeContext);
    if (!context->interrupted) {
      if (CancelIoEx(reinterpret_cast<HANDLE>(connection), context) != TRUE) {
        DWORD lastError = GetLastError();
        if (lastError != ERROR_NOT_FOUND) {
          throw std::runtime_error("TcpConnection::stop, CancelIoEx failed, result=" + std::to_string(GetLastError()));
        }
      }

      context->interrupted = true;
    }
  }

  stopped = true;
}
void FDirectoryWatchRequestWindows::EndWatchRequest()
{
	if ( !bEndWatchRequestInvoked && !bPendingDelete )
	{
		if ( DirectoryHandle != INVALID_HANDLE_VALUE )
		{
#if WINVER >= 0x600		// CancelIoEx() is only supported on Windows Vista and higher
			CancelIoEx(DirectoryHandle, &Overlapped);
#else
			CancelIo(DirectoryHandle);
#endif
			// Clear the handle so we don't setup any more requests, and wait for the operation to finish
			HANDLE TempDirectoryHandle = DirectoryHandle;
			DirectoryHandle = INVALID_HANDLE_VALUE;
			WaitForSingleObjectEx(TempDirectoryHandle, 1000, true);
			
			::CloseHandle(TempDirectoryHandle);
		}
		else
		{
			// The directory handle was never opened
			bPendingDelete = true;
		}

		// Only allow this to be invoked once
		bEndWatchRequestInvoked = true;
	}
}
示例#3
0
static void
tr_watchdir_win32_free (tr_watchdir_backend * backend_base)
{
  tr_watchdir_win32 * const backend = BACKEND_UPCAST (backend_base);

  if (backend == NULL)
    return;

  assert (backend->base.free_func == &tr_watchdir_win32_free);

  if (backend->fd != INVALID_HANDLE_VALUE)
    CancelIoEx (backend->fd, &backend->overlapped);

  if (backend->thread != NULL)
    {
      WaitForSingleObject (backend->thread, INFINITE);
      CloseHandle (backend->thread);
    }

  if (backend->event != NULL)
    bufferevent_free (backend->event);

  if (backend->notify_pipe[0] != TR_BAD_SOCKET)
    evutil_closesocket (backend->notify_pipe[0]);
  if (backend->notify_pipe[1] != TR_BAD_SOCKET)
    evutil_closesocket (backend->notify_pipe[1]);

  if (backend->fd != INVALID_HANDLE_VALUE)
    CloseHandle (backend->fd);

  tr_free (backend);
}
示例#4
0
AsyncIO::~AsyncIO() {
  if (*this) {
    if (CancelIoEx(m_fh, nullptr))
      waitForCompletion();
    CloseHandle(m_fh);
  }
}
void SarClient::stop()
{
    if (_mmNotificationClientRegistered) {
        _mmEnumerator->UnregisterEndpointNotificationCallback(
            _mmNotificationClient);
        _mmNotificationClientRegistered = false;
    }

    if (_mmNotificationClient) {
        _mmNotificationClient->Release();
        _mmNotificationClient = nullptr;
    }

    if (_mmEnumerator) {
        _mmEnumerator = nullptr;
    }

    if (_device != INVALID_HANDLE_VALUE) {
        CancelIoEx(_device, nullptr);
        CloseHandle(_device);
        _device = INVALID_HANDLE_VALUE;
    }

    if (_completionPort) {
        CloseHandle(_completionPort);
        _completionPort = nullptr;
    }
}
示例#6
0
文件: watch.cpp 项目: respu/yield
void Watch::close() {
  if (directory != NULL) {
    CancelIoEx(*directory, *this);
    directory->close();
    Directory::dec_ref(*directory);
    directory = NULL;
  }
}
示例#7
0
//------------------------------------------------------------------------------
void system_stopSyncThread(void)
{
    CancelIoEx(syncThreadInstance_l.hSyncThreadHandle, NULL);

    // Signal to stop the thread and wait for the thread to terminate
    syncThreadInstance_l.fThreadExit = TRUE;
    WaitForSingleObject(syncThreadInstance_l.hSyncThreadHandle, 1000);
}
示例#8
0
文件: async_io.c 项目: mlang/brltty
static void
cancelWindowsTransferOperation (OperationEntry *operation) {
  FunctionEntry *function = operation->function;
  DWORD count;

  if (CancelIoEx(function->fileDescriptor, &function->windows.overlapped)) {
    GetOverlappedResult(function->fileDescriptor, &function->windows.overlapped, &count, TRUE);
  }
}
示例#9
0
/**
 *@错误回调,从连接池中回收部分socket后,需要新增部分socket,否则最后可能socket资源耗尽,造成无法服务
 */
void iocp_onerror( iocp_overlapped*  &pOL ){
	
	CancelIoEx((HANDLE)pOL->m_skClient,&pOL->m_ol);
	shutdown( pOL->m_skClient, SD_BOTH);

	iocp_create_client( pOL->m_skServer , pOL->m_timeout );
	pOL->m_usenum = 0;

	//iocp_remove_form_map 清理发生错误的socket
}
示例#10
0
 void DirectoryWatcherImpl::setActive(const bool active)
 {
     if (!active && m_active && m_fileHandle)
     {
         m_active = false;
         CancelIoEx(m_fileHandle, NULL);
     }
 
     m_active = active;
 }
示例#11
0
 DirectoryWatcherImpl::~DirectoryWatcherImpl()
 {
     m_shouldClose = true;
     m_active = false;
 
     if (m_fileHandle)
         CancelIoEx(m_fileHandle, NULL);
 
     m_thread.join();
 }
	virtual ~FileSystemWatcherPC()
	{
		if (m_task)
		{
			CancelIoEx(m_task->m_handle, nullptr);
			CloseHandle(m_task->m_handle);

			m_task->destroy();
			LUMIX_DELETE(m_allocator, m_task);
		}
	}
示例#13
0
void CClient::Restart(NETOP curOp)
{
	CLock lock(&m_criticalSection);
	LOG("Restart client[%d], current status[%s] and operation[%s].", GetID(), NETSTATUSSTR[m_status], NETOPSTR[curOp]);
	switch (m_status)
	{
	case NETSTATUS_Dead:
		{
			if (curOp == NETOP_Accept)
				LOG("Cann't start client[%d].", GetID());
		}
		break;
	case NETSTATUS_Connected:
		{
			if (curOp == NETOP_Accept)
			{
				Stop();
				if (!Start())
					LOG("Fail to start client[%d].", GetID());
			}
		}
		break;
	case NETSTATUS_CompletionNotify:
		{
			if (CancelIoEx((HANDLE)m_socket, NULL) == 0)
			{
				if (GetLastError() != ERROR_NOT_FOUND)
					LOG("Client[%d] fail to call CancelIoEx.", GetID());
			}
			if (!AppendDisconnect(true))
			{
				LOG("Client[%d] fail to append disconnect.", GetID());
				Stop();
				if (!Start())
					LOG("Fail to start client[%d].", GetID());
			}
		}
		break;
	case NETSTATUS_Disconnecting:
	case NETSTATUS_Disconnected:
		{
			if (curOp==NETOP_Disconnect || curOp==NETOP_Accept)
			{
				Stop();
				if (!Start())
					LOG("Fail to start client[%d].", GetID());
			}
		}
		break;
	default:
		LOG("Client[%d] get an unexpected status[%s].", GetID(), NETSTATUSSTR[m_status]);
		break;
	}
}
示例#14
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);
}
示例#15
0
void triebWerk::CFileWatcher::StopWatching()
{
	m_Events.clear();
	m_Active = false;
	if (m_FileHandle != INVALID_HANDLE_VALUE)
	{
		//Stop the ReadDirectoryChangesW so the thread can be joined
		CancelIoEx(m_FileHandle, NULL);

		m_Thread.join();
	}
}
示例#16
0
AsyncIO& AsyncIO::operator=(AsyncIO&& other) {
  if (*this) {
    if (CancelIoEx(m_fh, nullptr))
      waitForCompletion();
    CloseHandle(m_fh);
  }
  m_fh = other.m_fh;
  other.m_fh = INVALID_HANDLE_VALUE;
  m_queue = std::move(other.m_queue);
  m_maxBlock = other.m_maxBlock;
  return *this;
}
示例#17
0
SocketSender::~SocketSender()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
# if defined(USE_WINDOWS8_API)
	BOOL result = CancelIoEx((HANDLE) m_s.GetSocket(), NULL);
	assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
# else
	BOOL result = CancelIo((HANDLE) m_s.GetSocket());
	assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
# endif
#endif
}
示例#18
0
void
DriverShutdown()
{
	// Signal to driver to stop and cancel any in-progress io operations
	SetEvent(g_hStopTheadEvent);
	if (g_hDriver != INVALID_HANDLE_VALUE) {
		// Canceling pending io operations
		CancelIoEx(g_hDriver, NULL);
	}
	// Wait for the thread which takes care of closing the device driver
	WaitForSingleObject(g_hThread, INFINITE);
	UnloadKernelDriver();
}
示例#19
0
static int win_close(w_stm_t stm) {
  struct win_handle *h = stm->handle;

  EnterCriticalSection(&h->mtx);

  if (h->read_pending) {
    if (CancelIoEx(h->h, &h->read_pending->olap)) {
      free(h->read_pending);
      h->read_pending = NULL;
    }
  }
  if (h->write_pending) {
    if (CancelIoEx(h->h, &h->write_pending->olap)) {
      free(h->write_pending);
      h->write_pending = NULL;
    }

    while (h->write_head) {
      struct write_buf *b = h->write_head;
      h->write_head = b->next;

      free(b->data);
      free(b);
    }
  }

  if (h->h != INVALID_HANDLE_VALUE) {
    CloseHandle(h->h);
    h->h = INVALID_HANDLE_VALUE;
  }

  if (h->waitable) {
    CloseHandle(h->waitable);
  }
  free(h);
  stm->handle = NULL;

  return 0;
}
示例#20
0
文件: pipe-win32.c 项目: AddictXQ/mpv
static void request_cancel(struct mp_input_src *src)
{
    struct priv *p = src->priv;

    MP_VERBOSE(src, "Exiting...\n");
    atomic_store(&p->cancel_requested, true);

    // The thread might not be peforming I/O at the exact moment when
    // CancelIoEx is called, so call it in a loop until it succeeds or the
    // thread exits
    do {
        if (CancelIoEx(p->file, NULL))
            break;
    } while (WaitForSingleObject(p->thread, 1) != WAIT_OBJECT_0);
}
示例#21
0
int
FilterThread(
    FILE* ChildOutput,
    DWORD millisecTimeout
    )
{
    FilterThreadData data = {
        ThreadId,
        &BufSize,
        &StartPointer,
        ThreadOut,
        ThreadFull,
        ChildOutput
    };

    HANDLE hThreadWorker = (HANDLE)_beginthreadex(nullptr, 0, FilterWorker, &data, 0, nullptr);

    if (hThreadWorker == 0) {
        LogError("Failed to create FilterWorker thread - error = %d", GetLastError());
        return -1;
    }

    DWORD waitresult = WaitForSingleObject(hThreadWorker, millisecTimeout);

    int rc = 0;

    if (waitresult == WAIT_TIMEOUT) {
        // Abort the worker thread by cancelling the IO operations on the pipe
        CancelIoEx((HANDLE)_get_osfhandle(_fileno(ChildOutput)), nullptr);
        WaitForSingleObject(hThreadWorker, INFINITE);
        rc = WAIT_TIMEOUT;
    }
    else {
        DWORD ec;
        if (!GetExitCodeThread(hThreadWorker, &ec)) {
            LogError("Could not get exit code from FilterWorker worker thread - error = %d", GetLastError());
            rc = -1;
        }
        if (ec != 0) {
            LogError("Pipe read failed - errno = %d\n", ec);
            rc = -1;
        }
    }

    CloseHandle(hThreadWorker);

    return rc;
}
示例#22
0
FileWatchdog::~FileWatchdog() {
	memset( m_WorkingDirectory, 0, FILENAME_MAX * sizeof( char ) );

	CancelIoEx( m_Watchdog, nullptr );
	CloseHandle( m_Watchdog );
	m_Watchdog = nullptr;

	if( m_ToReload.size() ) {
		file_watched_t* file = m_ToReload.front();

		while( file ) {
			m_ToReload.pop();
			SAFE_DELETE( file )
			if( !m_ToReload.size() ) break;
			file = m_ToReload.front();
		}

		file = nullptr;
	}
示例#23
0
void ipc_pipe_server_free(ipc_pipe_server_t *pipe)
{
	if (!pipe)
		return;

	if (pipe->thread) {
		CancelIoEx(pipe->handle, &pipe->overlap);
		SetEvent(pipe->ready_event);
		WaitForSingleObject(pipe->thread, INFINITE);
		CloseHandle(pipe->thread);
	}
	if (pipe->ready_event)
		CloseHandle(pipe->ready_event);
	if (pipe->handle)
		CloseHandle(pipe->handle);

	free(pipe->read_data);
	memset(pipe, 0, sizeof(*pipe));
}
示例#24
0
文件: Server.cpp 项目: aliakseis/IOCP
void Server::Destroy()
{
    m_ShuttingDown = true;

    if (m_AcceptTPWORK != NULL)
    {
        WaitForThreadpoolWorkCallbacks(m_AcceptTPWORK, true);
        CloseThreadpoolWork(m_AcceptTPWORK);
        m_AcceptTPWORK = NULL;
    }

    if (m_listenSocket != INVALID_SOCKET)
    {
        Network::CloseSocket(m_listenSocket);
        CancelIoEx(reinterpret_cast<HANDLE>(m_listenSocket), NULL);
        m_listenSocket = INVALID_SOCKET;
    }

    if (m_pTPIO != NULL)
    {
        WaitForThreadpoolIoCallbacks(m_pTPIO, true);
        CloseThreadpoolIo(m_pTPIO);
        m_pTPIO = NULL;
    }

    if (m_ClientTPCLEAN != NULL)
    {
        CloseThreadpoolCleanupGroupMembers(m_ClientTPCLEAN, false, NULL);
        CloseThreadpoolCleanupGroup(m_ClientTPCLEAN);
        DestroyThreadpoolEnvironment(&m_ClientTPENV);
        m_ClientTPCLEAN = NULL;
    }

    EnterCriticalSection(&m_CSForClients);
    for (auto client : m_Clients)
    {
        delete client;
    }
    m_Clients.clear();
    LeaveCriticalSection(&m_CSForClients);

    DeleteCriticalSection(&m_CSForClients);
}
示例#25
0
void Socket::CloseSocket()
{
	if (m_s != INVALID_SOCKET)
	{
#ifdef USE_WINDOWS_STYLE_SOCKETS
# if defined(USE_WINDOWS8_API)
		BOOL result = CancelIoEx((HANDLE) m_s, NULL);
		assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
		CheckAndHandleError_int("closesocket", closesocket(m_s));
# else
		BOOL result = CancelIo((HANDLE) m_s);
		assert(result || (!result && GetLastError() == ERROR_NOT_FOUND));
		CheckAndHandleError_int("closesocket", closesocket(m_s));
# endif
#else
		CheckAndHandleError_int("close", close(m_s));
#endif
		m_s = INVALID_SOCKET;
		SocketChanged();
	}
}
示例#26
0
void CEXIETHERNET::Deactivate()
{
  if (!IsActivated())
    return;

  // Signal read thread to exit.
  readEnabled.Clear();
  readThreadShutdown.Set();

  // Cancel any outstanding requests from both this thread (writes), and the read thread.
  CancelIoEx(mHAdapter, nullptr);

  // Wait for read thread to exit.
  if (readThread.joinable())
    readThread.join();

  // Clean-up handles
  CloseHandle(mReadOverlapped.hEvent);
  CloseHandle(mWriteOverlapped.hEvent);
  CloseHandle(mHAdapter);
  mHAdapter = INVALID_HANDLE_VALUE;
  memset(&mReadOverlapped, 0, sizeof(mReadOverlapped));
  memset(&mWriteOverlapped, 0, sizeof(mWriteOverlapped));
}
TcpConnection TcpListener::accept() {
  assert(dispatcher != nullptr);
  assert(context == nullptr);
  if (dispatcher->interrupted()) {
    throw InterruptedException();
  }

  std::string message;
  SOCKET connection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (connection == INVALID_SOCKET) {
    message = "socket failed, " + errorMessage(WSAGetLastError());
  } else {
    uint8_t addresses[sizeof sockaddr_in * 2 + 32];
    DWORD received;
    TcpListenerContext context2;
    context2.hEvent = NULL;
    if (acceptEx(listener, connection, addresses, 0, sizeof(sockaddr_in) + 16, sizeof(sockaddr_in) + 16, &received, &context2) == TRUE) {
      message = "AcceptEx returned immediately, which is not supported.";
    } else {
      int lastError = WSAGetLastError();
      if (lastError != WSA_IO_PENDING) {
        message = "AcceptEx failed, " + errorMessage(lastError);
      } else {
        context2.context = dispatcher->getCurrentContext();
        context2.interrupted = false;
        context = &context2;
        dispatcher->getCurrentContext()->interruptProcedure = [&]() {
          assert(dispatcher != nullptr);
          assert(context != nullptr);
          TcpListenerContext* context2 = static_cast<TcpListenerContext*>(context);
          if (!context2->interrupted) {
            if (CancelIoEx(reinterpret_cast<HANDLE>(listener), context2) != TRUE) {
              DWORD lastError = GetLastError();
              if (lastError != ERROR_NOT_FOUND) {
                throw std::runtime_error("TcpListener::stop, CancelIoEx failed, " + lastErrorMessage());
              }

              context2->context->interrupted = true;
            }

            context2->interrupted = true;
          }
        };

        dispatcher->dispatch();
        dispatcher->getCurrentContext()->interruptProcedure = nullptr;
        assert(context2.context == dispatcher->getCurrentContext());
        assert(dispatcher != nullptr);
        assert(context == &context2);
        context = nullptr;
        DWORD transferred;
        DWORD flags;
        if (WSAGetOverlappedResult(listener, &context2, &transferred, FALSE, &flags) != TRUE) {
          lastError = WSAGetLastError();
          if (lastError != ERROR_OPERATION_ABORTED) {
            message = "AcceptEx failed, " + errorMessage(lastError);
          } else {
            assert(context2.interrupted);
            if (closesocket(connection) != 0) {
              throw std::runtime_error("TcpListener::accept, closesocket failed, " + errorMessage(WSAGetLastError()));
            } else {
              throw InterruptedException();
            }
          }
        } else {
          assert(transferred == 0);
          assert(flags == 0);
          if (setsockopt(connection, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, reinterpret_cast<char*>(&listener), sizeof listener) != 0) {
            message = "setsockopt failed, " + errorMessage(WSAGetLastError());
          } else {
            if (CreateIoCompletionPort(reinterpret_cast<HANDLE>(connection), dispatcher->getCompletionPort(), 0, 0) != dispatcher->getCompletionPort()) {
              message = "CreateIoCompletionPort failed, " + lastErrorMessage();
            } else {
              return TcpConnection(*dispatcher, connection);
            }
          }
        }
      }
    }

    int result = closesocket(connection);
    assert(result == 0);
  }

  throw std::runtime_error("TcpListener::accept, " + message);
}
示例#28
0
VOID
UserScanSynchronizedCancel (
    _In_  PUSER_SCAN_CONTEXT Context
    )
/*++

Routine Description:

    This routine tries to abort all the scanning threads and wait for them to terminate.

Arguments:

    Context    - User scan context, please see userscan.h

Return Value:

    Please consult WaitForMultipleObjects(...)

--*/
{
    ULONG i;
    PSCANNER_THREAD_CONTEXT  scanThreadCtxes = Context->ScanThreadCtxes;
    
    if (NULL == scanThreadCtxes) {
        fprintf(stderr, "Scan thread contexes are NOT suppoed to be NULL.\n");
        return;
    }
    
    //
    //  Tell all scanning threads that the program is going to exit.
    //
    
    Context->Finalized = TRUE;
    
    //
    //  Signal cancellation events for all scanning threads.
    //
    
    for (i = 0;
         i < USER_SCAN_THREAD_COUNT;
         i ++ ) {
         
        scanThreadCtxes[i].Aborted = TRUE;
    }
    
    //
    //  Wake up the listening thread if it is waiting for message 
    //  via GetQueuedCompletionStatus() 
    //
    
    CancelIoEx(Context->ConnectionPort, NULL);
    
    //
    //  Wait for all scan threads to complete cancellation, 
    //  so we will be able to close the connection port and etc.
    //
    
    WaitForAll(scanThreadCtxes);

    return;
}
示例#29
0
void ImageMaker::stop() {
    CancelIoEx(m_driveHandle, nullptr);
    m_shouldHalt.signal();
}
	virtual ~FileSystemWatcherPC() 
	{
		CancelIoEx(m_handle, nullptr);
		CloseHandle(m_handle);
	}