How to force close with ZwReadFile

When a device sends data out the serial COM port, I am reading with ZwReadFile. This works very well.

When the device stops sending data through the COM serial port, then I want to use ZwClose.
But, it does not allow me to close with the ZwClose. Because ZwReadFile is waiting for some data to arrive.

How can I force close or use ZwClose?

use async io and the OS will cancel your read(s) when you call zwclose.

Mark Roddy

@Mark_Roddy said:
use async io and the OS will cancel your read(s) when you call zwclose.

Mark Roddy

Thanks for your answer. Please, could you explain a little more about async io?
Where can I find examples with async ios?

Is this a user-mode question? If so, have you tried calling CancelIoEx?

Peter

Wait… don’t we have another discussion by this same poster on this topic? Apparently, this is in kernel mode?.

(Let’s move to the other thread)

@ryujiK said:
When a device sends data out the serial COM port, I am reading with ZwReadFile. This works very well.

When the device stops sending data through the COM serial port, then I want to use ZwClose.
But, it does not allow me to close with the ZwClose. Because ZwReadFile is waiting for some data to arrive.

How can I force close or use ZwClose?

This is actually a good example of understanding the differences between the ZwXX functions and the WdfIoXX ones … in both cases under the hoods the driver is telling the OS “go do something” and the OS make a little post-it note and passes that to the part of the OS responsible for actually moving the data around [google “IRP”]. Once that post-it note has been written and passed along, if you want to tell the OS “wait, stop, don’t do that!” then you have to make a cancel request for that post-it, tell the OS about it and hope that the “cancel” request happens before the post-it is completed. Ick.

With the ZwXX functions if you want to tell the OS to “give up if things aren’t working” that’s what you have to do, and it’s a hassle and fraught with danger. Looking at the WdfIoXX functions, however, you notice that they have a “Timeout” variable which isn’t on the ZwXX functions … that “Timeout” essentially tells the OS “if you can’t do this by this time then just forget about it” which is exactly what you want to do …

So, in your specific case what I would suggest is using the WdfIoXX functions to attempt to read data from the serial port with a timeout that works for you, say 5sec. When the function completes if it returns “timeout” then you can close the ioTarget and you’re done …

But in all cases, first do some GoogleFu as well as searching the archives here … and then ask your question as a problem, not as a solution “… how can I stop trying to read from a serial port if no data arrives” or something similar, not “… I am trying to call ZwClose on a serial port, should I use a timer for that?” …