循环式读取管道过程中防止出现死循环

窗口程序使用Pipe与控制台程序交流,读取控制台程序输出的信息,一般是使用while循环配套ReadFile函数。问题是,如果控制台程序暂时没有输出并且没有退出,ReadFile函数将一直等待,导致死循环。方法是在使用ReadFile之前,加入PeekNamedPipe函数调用,请看以下函数:

CString ChessBoard::ReadEngine(DWORD* pDwRead){
    DWORD nBytesToRead = 0;
    char temp[1024] = {0};
    CString msgOut;
    if(hOutputRead){
        while(1){
            PeekNamedPipe(hOutputRead,temp,1024,&nBytesToRead,0,0);
            if(nBytesToRead){
                if(ReadFile(hOutputRead,temp,nBytesToRead,pDwRead,NULL)== NULL){
                    break;
                }
                msgOut += temp;
            }else{
                break;
            }
        }
    }
    return msgOut;
}

 MSDN上PeekNamedPipe和ReadFile的区别:

最重要的是两点:1、PeekNamedPipe立即返回;2、PeekNamedPipe不会清除管道输出端数据,而ReadFile清除。

The PeekNamedPipe function is similar to the ReadFile function with the following exceptions:

 

    The data is read in the mode specified with CreateNamedPipe. For example, create a pipe with PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE. If you change the mode to PIPE_READMODE_BYTE with SetNamedPipeHandleState, ReadFile will read in byte mode, but PeekNamedPipe will continue to read in message mode.
    The data read from the pipe is not removed from the pipe's buffer.
    The function always returns immediately, even if there is no data in the pipe. The wait mode of a named pipe handle (blocking or nonblocking) has no effect on the function.
    The function can return additional information about the contents of the pipe.

If the specified handle is a named pipe handle in byte-read mode, the function reads all available bytes up to the size specified in nBufferSize. For a named pipe handle in message-read mode, the function reads the next message in the pipe. If the message is larger than nBufferSize, the function returns TRUE after reading the specified number of bytes. In this situation, lpBytesLeftThisMessage will receive the number of bytes remaining in the message.

posted on 2013-09-21 10:04  cpp520  阅读(4056)  评论(0)    收藏  举报

导航