简体   繁体   English

无法打开 pipe。 GLE=2

[英]Could not open pipe. GLE=2

I'm trying to interact with pipes: C# server -> C++ client我正在尝试与管道交互: C# 服务器 -> C++ 客户端

I don't need something really complex, if the server is able to send data to client it's more than enough我不需要真正复杂的东西,如果服务器能够向客户端发送数据就足够了

I don't know why I'm getting this error: Could not open pipe.我不知道为什么会出现此错误:无法打开 pipe。 GLE=2 GLE=2

I'm using Microsoft examples C++ client and C# server我正在使用 Microsoft 示例C++ 客户端C# 服务器

This is what I'm trying to do:这就是我想要做的:

C# SERVER C# 服务器

    private void Form1_Load(object sender, EventArgs e)
    {
        Thread t = new Thread(Server);
        t.IsBackground = true;
        t.Start();
    }

    private void Server()
    {
        while (true)
        {
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("mynamedpipe", PipeDirection.Out))
            {
                Console.WriteLine("NamedPipeServerStream object created.");

                // Wait for a client to connect
                Console.Write("Waiting for client connection...");
                pipeServer.WaitForConnection();

                Console.WriteLine("Client connected.");
                try
                {
                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        sw.WriteLine("testing msg");
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException err)
                {
                    Console.WriteLine("ERROR: {0}", err.Message);
                }
            }
        }            
    }

C++ CLIENT C++ 客户端

#include <conio.h>
#include "pch.h"
#include <windows.h> 
#include <stdio.h> 
#include <tchar.h>
#include <strsafe.h>
#include "client.h"

#define BUFSIZE 512

int _tmain()
{
    HANDLE hPipe;
    LPCTSTR lpvMessage = TEXT("Default message from client.");
    TCHAR  chBuf[BUFSIZE];
    BOOL   fSuccess = FALSE;
    DWORD  cbRead, cbToWrite, cbWritten, dwMode;
    LPCTSTR lpszPipename = TEXT("mynamedpipe");    

    // Try to open a named pipe; wait for it, if necessary. 

    while (1)
    {
        hPipe = CreateFile(
            lpszPipename,   // 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 

      // Break if the pipe handle is valid. 

        if (hPipe != INVALID_HANDLE_VALUE)
            break;

        // Exit if an error other than ERROR_PIPE_BUSY occurs. 

        if (GetLastError() != ERROR_PIPE_BUSY)
        {
            _tprintf(TEXT("Could not open pipe. GLE=%d\n"), GetLastError());
            return -1;
        }

        // All pipe instances are busy, so wait for 20 seconds. 

        if (!WaitNamedPipe(lpszPipename, 20000))
        {
            printf("Could not open pipe: 20 second wait timed out.");
            return -1;
        }
    }

    // The pipe connected; change to message-read mode. 

    dwMode = PIPE_READMODE_MESSAGE;
    fSuccess = SetNamedPipeHandleState(
        hPipe,    // pipe handle 
        &dwMode,  // new pipe mode 
        NULL,     // don't set maximum bytes 
        NULL);    // don't set maximum time 
    if (!fSuccess)
    {
        _tprintf(TEXT("SetNamedPipeHandleState failed. GLE=%d\n"), GetLastError());
        return -1;
    }

    // Send a message to the pipe server. 

    cbToWrite = (lstrlen(lpvMessage) + 1) * sizeof(TCHAR);
    _tprintf(TEXT("Sending %d byte message: \"%s\"\n"), cbToWrite, lpvMessage);

    fSuccess = WriteFile(
        hPipe,                  // pipe handle 
        lpvMessage,             // message 
        cbToWrite,              // message length 
        &cbWritten,             // bytes written 
        NULL);                  // not overlapped 

    if (!fSuccess)
    {
        _tprintf(TEXT("WriteFile to pipe failed. GLE=%d\n"), GetLastError());
        return -1;
    }

    printf("\nMessage sent to server, receiving reply as follows:\n");

    do
    {
        // Read from the pipe. 

        fSuccess = ReadFile(
            hPipe,    // pipe handle 
            chBuf,    // buffer to receive reply 
            BUFSIZE * sizeof(TCHAR),  // size of buffer 
            &cbRead,  // number of bytes read 
            NULL);    // not overlapped 

        if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
            break;

        _tprintf(TEXT("\"%s\"\n"), chBuf);
    } while (!fSuccess);  // repeat loop if ERROR_MORE_DATA 

    if (!fSuccess)
    {
        _tprintf(TEXT("ReadFile from pipe failed. GLE=%d\n"), GetLastError());
        return -1;
    }

    printf("\n<End of message, press ENTER to terminate connection and exit>");
    _getch();

    CloseHandle(hPipe);

    return 0;
}

EDIT:编辑:

Changed the error print line to this:将错误打印行更改为:

std::error_code ec{ static_cast<std::int32_t>(GetLastError()), std::system_category() };
_tprintf(TEXT("WriteFile to pipe failed. GLE=%d\n"));
_tprintf(ec.message().c_str);
return -1;

The pipe name you used on the C++ side is incorrect.您在C++端使用的 pipe 名称不正确。 It should be: "\\\\.\\pipe\\mynamedpipe" .它应该是: "\\\\.\\pipe\\mynamedpipe"

Also, change the C# side to the following:此外,将C#侧更改为以下内容:

using ( var pipeServer = new NamedPipeServerStream( "mynamedpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message ) ) { }

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

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