From b520457b14f9b5570a6bae5afde4f6967863bd71 Mon Sep 17 00:00:00 2001 From: Morteza Aghazamani Date: Sun, 3 Oct 2021 12:52:34 +0330 Subject: [PATCH] "Cancel" Implementation(windows only): Cancels all pending read and write operation from an other thread. Unix also need add something like this. --- include/serial/impl/win.h | 3 +++ include/serial/serial.h | 4 ++++ src/impl/win.cc | 18 ++++++++++++++++++ src/serial.cc | 6 ++++++ 4 files changed, 31 insertions(+) diff --git a/include/serial/impl/win.h b/include/serial/impl/win.h index 2c0c6cd..4e20b7e 100644 --- a/include/serial/impl/win.h +++ b/include/serial/impl/win.h @@ -66,6 +66,9 @@ public: void open (); + void + cancel(); + void close (); diff --git a/include/serial/serial.h b/include/serial/serial.h index a165785..0685437 100644 --- a/include/serial/serial.h +++ b/include/serial/serial.h @@ -211,6 +211,10 @@ public: bool isOpen () const; + /*! Cancels all pending read and write operation. */ + void + cancel(); + /*! Closes the serial port. */ void close (); diff --git a/src/impl/win.cc b/src/impl/win.cc index 889e06f..599402d 100644 --- a/src/impl/win.cc +++ b/src/impl/win.cc @@ -274,9 +274,27 @@ Serial::SerialImpl::reconfigurePort () } } +void +Serial::SerialImpl::cancel() +{ + if (is_open_ == true) { + if (fd_ != INVALID_HANDLE_VALUE) { + int ret; + ret = CancelIoEx(fd_, NULL); + DWORD last_error = GetLastError(); + if (ret == 0 && last_error != ERROR_NOT_FOUND) { + stringstream ss; + ss << "Error while canceling serial port: " << last_error; + THROW(IOException, ss.str().c_str()); + } + } + } +} + void Serial::SerialImpl::close () { + this->cancel(); if (is_open_ == true) { if (fd_ != INVALID_HANDLE_VALUE) { int ret; diff --git a/src/serial.cc b/src/serial.cc index a9e6f84..74abecc 100755 --- a/src/serial.cc +++ b/src/serial.cc @@ -83,6 +83,12 @@ Serial::open () pimpl_->open (); } +void +Serial::cancel() +{ + pimpl_->cancel(); +} + void Serial::close () {