簡體   English   中英

ReadFile(客戶端命名管道)掛起 - Win32 VC ++

[英]ReadFile(Client end named pipe) Hangs - Win32 VC++

我將以下代碼作為另一個向客戶端發送消息的模塊的一部分。 這是針對IPC的。 兩個dll由exe加載,這兩個需要通信

在DLL-1中,我將以下代碼行作為名為pipe的服務器。

pipe = CreateNamedPipe("\\\\.\\pipe\\S2D8",PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED /**1-way, send only with overlapped IO*/,
        PIPE_TYPE_MESSAGE,1,0,0, 0, NULL);
    if( INVALID_HANDLE_VALUE != pipe )
    {
        log("Created Named Pipe as Serverl\n");     
    }
    else 
    {
        log("Cannot create Named Pipe as Server\n");        
    }

在DLL-1中的其他地方,我有以下服務器

bool result = ConnectNamedPipe(pipe, NULL);
            if (!result)
            {
                CloseHandle(pipe); // close the pipe

            }
            else
            {
                DWORD numWritten;
                WriteFile(pipe,KeyBoardBuffer,strlen(KeyBoardBuffer) * sizeof(char),&numWritten,0);
                log("Bytes writtern to pipe:%d\n",numWritten);
            }

當我查看日志時,我可以看到那個命名管道。 目前很好。

在DLL-2中,我將以下內容作為客戶端部分

log("Connecting to named pipe at client\n");
        if(pipe2 == NULL || pipe2 == INVALID_HANDLE_VALUE)
        {

            pipe2 = CreateFile("\\\\.\\pipe\\S2D8", GENERIC_READ , 
                FILE_SHARE_READ | FILE_SHARE_WRITE,NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);

            if (pipe2 == INVALID_HANDLE_VALUE)
            {
                log("Cannot connect to named pipe at client%x\n", GetLastError());
                CloseHandle(pipe2);
            }
            else
            {
                log("Connected to named pipe at client! Going to read!!!\n");
                char buffer[256] = {'\0'};
                DWORD numBytesRead = 0;
                BOOL result = ReadFile(
                    pipe2,
                    buffer, // the data from the pipe will be put here
                    sizeof(buffer) * sizeof(char), // number of bytes allocated
                    &numBytesRead, // this will store number of bytes actually read
                    NULL // not using overlapped IO
                    );
                if (result) 
                {
                    kbBuffer[numBytesRead / sizeof(char)] = '\0'; // null terminate the string
                    log( "Number of bytes read: %d\n",numBytesRead);
                    log(kbBuffer );
                }
                else 
                {
                    log("Failed to read data from the pipe.\n");                
                }
            }
        }

在我的日志中,我可以看到“連接到客戶端的命名管道”,然后“連接到客戶端的命名管道!繼續閱讀!!!”,之后日志中沒有任何內容,一切似乎都停滯不前。

管道的命名約定是否正確? 或者我必須定義任何安全設置嗎?

我正在使用VS2010,Win7 x64。

任何指導都非常感謝。

你說的是錯誤的方法。 管道應該預先存在,所以你應該調用OpenFile() ,而不是CreateFile()

啊,我找到了掛起的答案,我不得不做一個PeekNamedPipe(pipe2, NULL, 0, NULL, &bytesAvailable, NULL); 然后在我執行ReadFile()之前檢查bytesAvailable是否大於零

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM