0

When I do not set timeout settings via GetTimeout & SetTimeout after I connect my USB-UART converter to my laptop, the ReadFile becomes blocking. However, once I set them via SetTimeOut, the ReadFile is not blocking anymore and returns true even if the given number of bytes were not read.

When ReadFile returns true but the dwRead parameter says 0 since no data was going into my PC via serial port, I conclude that the ReadFile function must have timed out. However, using GetLastError returns 0. How can I be verify in my C++ program that the ReadFile has actually timedout?

19
  • Did it transfer any bytes?
    – user207421
    Jul 13, 2016 at 23:30
  • 1
    When ReadFile returns true but the dwRead parameter says 0 [...] I conclude that the ReadFile function must have timed out - for a serial port handle, I believe this is a safe conclusion. If there were any other reason, the call would have failed. Jul 13, 2016 at 23:33
  • OK, I will use that in my program. At this time I have only the USB-UART converter connected to my laptop, there is no device on the other end of the coverter so data is being read in.
    – quantum231
    Jul 13, 2016 at 23:36
  • 1
    main - in this case you never becomes blocking. ZwReadFile return STATUS_PENDING. when operation completed - looking for iosb.Information (number of bytes readed) and iosb.Status - final status of operation. in case timeout Information will be 0 and Status != 0
    – RbMm
    Jul 14, 2016 at 1:04
  • 1
    @RbMm: there are some situations in which using the kernel API from user mode is excusable. This isn't one of them. The Win32 API supports asynchronous I/O perfectly well. Jul 14, 2016 at 2:43

2 Answers 2

3

When using SetCommTimeouts() with ReadFile(), the COMMTIMEOUTS documentation says:

ReadIntervalTimeout
The maximum time allowed to elapse before the arrival of the next byte on the communications line, in milliseconds. If the interval between the arrival of any two bytes exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.

If a timeout occurs, the read is complete (ReadFile() returns TRUE), and the number of bytes that had been buffered before the timeout elapsed is reflected in your dwRead variable. So, you will know if a timeout occurred if dwRead is less than the number of bytes you asked ReadFile() to read. If there was no buffered data, dwRead will be 0. If dwRead is equal to the number of bytes you asked for, there was no timeout since ReadFile() exited when the last requested byte was read.

4
  • Very good. Strange design, nicht war? Compare read(): it blocks until at least one byte is transferred or end of stream or an error occured, including a timeout. No nonsense about timeouts between bytes, which makes the timeout value very difficult to establish usefully.
    – user207421
    Jul 14, 2016 at 1:25
  • read() can deal with timeouts between bytes, setting a reading timeout can cause it to fail with an ETIMEDOUT error code, same with a blocking recv(). I think an alternative design for ReadFile() would have been for it to fail with an ERROR_TIMEOUT error code. Jul 14, 2016 at 1:38
  • read() cannot deal with timeouts between bytes, as it will have returned the first bytes received before the timeout. The timeout can only occur before receiving any bytes.
    – user207421
    Jul 14, 2016 at 1:58
  • but if use NT api, like NtReadFile - you will got iosb.Status == STATUS_TIMEOUT on timeout - and this is simplest and most accurate way
    – RbMm
    Jul 14, 2016 at 12:12
-4

most simplest and accurate way use NT api NtReadFile and check final status of operation. timeout <=> iosb.Status == STATUS_TIMEOUT. kernel32 api ReadFile - lost info for this status(STATUS_TIMEOUT), because it check only for STATUS_PENDING and 0 > status

for synchronous work, can use code like this:

void SyncTest(POBJECT_ATTRIBUTES poa)
{
    HANDLE hFile;
    IO_STATUS_BLOCK iosb;
    NTSTATUS status = NtOpenFile(&hFile, FILE_ALL_ACCESS, poa, &iosb, FILE_SHARE_VALID_FLAGS, FILE_SYNCHRONOUS_IO_NONALERT);
    if (0 <= status)
    {
        SERIAL_TIMEOUTS st = { 4000, 1, 0, 1, 0 };
        status = NtDeviceIoControlFile(hFile, 0, 0, 0, &iosb, IOCTL_SERIAL_SET_TIMEOUTS, &st, sizeof(st), 0, 0);
        DbgPrint("time %x[%x,%p]\n", status, iosb.Status, iosb.Information);
        if (0 <= status)
        {
            UCHAR buf[256];
            status = NtReadFile(hFile, 0, 0, 0, &iosb, buf, sizeof(buf), 0, 0);
            DbgPrint("read %x [%x,%p]\n", status, iosb.Status, iosb.Information);
            //assert(status == iosb.Status);
            if (status == STATUS_TIMEOUT)
            {
                DbgPrint("timeout\n");
            }
        }
        NtClose(hFile);
    }
}

for asynchronous:

class __declspec(novtable) IoObject 
{
    friend class UserIrp;
protected:
    HANDLE _hFile;
private:
    LONG _dwRef;

protected:
    virtual ~IoObject()
    {
        if (_hFile) NtClose(_hFile);
    }
    virtual void OnIoComplete(NTSTATUS status, ULONG_PTR Information, ULONG code, PVOID pv) = 0;
public:

    NTSTATUS BindIoCompletion();

    void AddRef()
    {
        InterlockedIncrement(&_dwRef);
    }

    void Release()
    {
        if (!InterlockedDecrement(&_dwRef)) delete this;
    }

    IoObject()
    {
        _hFile = 0;
        _dwRef = 1;
    }
};

class UserIrp : public IO_STATUS_BLOCK
{
    friend IoObject;

    IoObject* _pObj;
    PVOID _pv;
    LONG _dwRef;
    ULONG _code;

    static VOID WINAPI OnComplete(NTSTATUS Status, ULONG_PTR Information, UserIrp* This)
    {
        This->_pObj->OnIoComplete(Status, Information, This->_code, This->_pv);
        This->Release();
    }

    ~UserIrp()
    {
        _pObj->Release();
    }

public:

    NTSTATUS CheckStatus(NTSTATUS status)
    {
        if (NT_ERROR(status))
        {
            OnComplete(status, Information, this);
        }

        return status;
    }

    void AddRef()
    {
        InterlockedIncrement(&_dwRef);
    }

    void Release()
    {
        if (!InterlockedDecrement(&_dwRef)) delete this;
    }

    UserIrp(IoObject* pObj, ULONG code, PVOID pv) : _pObj(pObj), _dwRef(1), _code(code), _pv(pv)
    {
        pObj->AddRef();
    }
};

NTSTATUS IoObject::BindIoCompletion()
{
    return RtlSetIoCompletionCallback(_hFile, (LPOVERLAPPED_COMPLETION_ROUTINE)UserIrp::OnComplete, 0);
}

class MySerial : public IoObject
{
    void OnIoComplete(NTSTATUS status, ULONG_PTR Information, ULONG code, PVOID pv)
    {
        DbgPrint("OnIoComplete(%x, %p, %.4s, %p)\n", status, Information, &code, pv);

        switch (code)
        {
        case 'time':
            if (0 <= status)
            {
                if (PUCHAR buf = new UCHAR[256])
                {
                    if (UserIrp* Irp = new UserIrp(this, 'read', buf))
                    {
                        static LARGE_INTEGER ByteOffset;
                        status = Irp->CheckStatus(NtReadFile(_hFile, 0, 0, Irp, Irp, buf, 256, &ByteOffset, 0));
                        DbgPrint("read begin = %x\n", status);
                        return ;
                    }
                    delete buf;
                }
            }
            break;
        case 'read':
            DbgPrint("read end(%x, %p)\n", status, Information);
            if (status == STATUS_TIMEOUT)
            {
                DbgPrint("timeout\n");
            }
            delete pv;
            break;
        }
    }

    virtual ~MySerial()
    {
        DbgPrint("--MySerial<%p>\n", this);
    }

public:

    MySerial()
    {
        DbgPrint("++MySerial<%p>\n", this);
    }

    NTSTATUS Open(POBJECT_ATTRIBUTES poa)
    {
        IO_STATUS_BLOCK iosb;
        return NtOpenFile(&_hFile, FILE_ALL_ACCESS, poa, &iosb, FILE_SHARE_VALID_FLAGS, 0);
    }

    NTSTATUS SetTimeouts(ULONG ms)
    {
        if (UserIrp* Irp = new UserIrp(this, 'time', 0))
        {
            SERIAL_TIMEOUTS st = { ms, 1, 0, 1, 0 };
            return Irp->CheckStatus(ZwDeviceIoControlFile(_hFile, 0, 0, Irp, Irp, IOCTL_SERIAL_SET_TIMEOUTS, &st, sizeof(st), 0, 0));
        }

        return STATUS_INSUFFICIENT_RESOURCES;
    }
};

void AsyncTest(POBJECT_ATTRIBUTES poa)
{
    if (MySerial* p = new MySerial)
    {
        if (0 <= p->Open(poa) && 0 <= p->BindIoCompletion())
        {
            NTSTATUS status = p->SetTimeouts(4000);
            DbgPrint("set timeout=%x\n", status);
        }
        p->Release();
    }
}
2
  • There sure are a lot of ways of doing things here
    – quantum231
    Jul 18, 2016 at 12:47
  • @quantum231 use native api most accurate way - simply need check final NTSTATUS of operation. in your case - this will be STATUS_TIMEOUT. not need check byte count, GetLastError, etc
    – RbMm
    Jul 18, 2016 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.