简体   繁体   English

命名管道读取超时

[英]Named-pipe reading timeout

I'm trying to set a timeout to the reading operation of my named pipe. 我正在尝试为我的命名管道的读取操作设置超时。
In order to read from the named pipe, I'm using the ReadFile function. 为了从命名管道读取,我正在使用ReadFile函数。
I read that a timeout can be set for this function with the SetCommTimeouts function but when I try to use it, I get system error 1: "Incorrect function". 我读到可以使用SetCommTimeouts函数为此函数设置超时,但是当我尝试使用它时,我得到系统错误1:“函数不正确”。
Here is my code (this is the client side): 这是我的代码(这是客户端):

m_pipe = CreateFileA(pipeName,   // pipe name 
                         GENERIC_READ |  // read and write access 
                         GENERIC_WRITE, 
                         0,              // no sharing 
                         NULL,           // default security attributes
                         OPEN_EXISTING,  // opens existing pipe 
                         0,              // default attributes 
                         NULL);          // no template file 

    if (m_pipe != INVALID_HANDLE_VALUE)
    {
            DWORD mode = PIPE_READMODE_MESSAGE | PIPE_WAIT;
            ok = SetNamedPipeHandleState(m_pipe, &mode, NULL, NULL);
            COMMTIMEOUTS cto;
            cto.ReadTotalTimeoutConstant = 1000;
            BOOL time = SetCommTimeouts(m_pipe, &cto);
    }

Am I doing something wrong or the SetCommTimeouts method is not supposed to be used with pipes? 我做错了什么或者SetCommTimeouts方法不应该与管道一起使用? Is there any other way to get a reading timeout? 有没有其他方法可以获得读取超时?

If the purpose of the timeout is to not get stuck forever you may consider a call to PeekNamedPipe(...) in a timed loop. 如果超时的目的是forever不会卡住,你可以考虑在定时循环中调用PeekNamedPipe(...) This way you can check whether there is anything to read from time to time. 这样您就可以检查是否有任何东西需要不时阅读。 Alternatively PeekNamedPipe may be used to decide whether a read on the pipe is actually going to get anything before the read is performed. 或者,可以使用PeekNamedPipe来确定执行读取之前管道上的读取是否实际上将获得任何内容。 This way a "waiting" read can be avoided. 这样可以避免“等待”读取。

You cannot use SetCommTimeouts with named pipes. 您不能将SetCommTimeouts与命名管道一起使用。 If you want timeouts, you will have to use Async I/O and implement the timeout yourself using CancelIo or CancelIoEx 如果您想要超时,则必须使用异步I / O并使用CancelIoCancelIoEx实现超时

ReadFile blocks until it read requested amount of bytes or error/abort happen. ReadFile阻塞,直到它读取请求的字节数或错误/中止发生。 Overlapped works same, ie it completes on same conditions. 重叠工作相同,即它在相同条件下完成。 Tried to implement timeouts using CancelIoEx and figured out that it loses data. 试图使用CancelIoEx实现超时,并发现它丢失了数据。 Until now see no way to implement timeouts and read only part of requested amount of bytes, or read cached data. 到目前为止,看不到实现超时的方法,只读取部分请求的字节数,或读取缓存的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM