为什么我的 NamedPipe 用空格分隔字符串?

DNS*_*zus 1 c++ operating-system pipe

我正在制作一个简单的客户端服务器管道示例作为练习。服务器将使用命名管道从客户端接收字符串。服务器将从客户端接收到的字符串中每个字符的大小写反转,并使用管道将字符串发送回客户端。它有效,但我写入管道的字符串似乎被空格打破了。随附的图片显示了我的问题。

我在服务器上创建一个像这样的命名管道。

HANDLE pipe_handle = CreateNamedPipe( PIPE_REV_NAME, //name PIPE_ACCESS_DUPLEX, //openMode PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, //Pipe Mode 1,//Max Instances 1024,//OutBuffSize 1024,//InBuffSize NMPWAIT_USE_DEFAULT_WAIT, NULL);

并在服务器上对其进行读取和写入,如下所示:

    DWORD bytes_read;
    ReadFile(
        pipe_handle,
        (LPVOID)string_to_reverse,
        MAX_PIPE_REVLEN - 1,
        &bytes_read,
        NULL);  
    string_to_reverse[bytes_read] = '\0';
    printf("Recieved: %s\n", string_to_reverse);
    cap_reverse(string_to_reverse, bytes_read);
    printf("Sending: %s\n", string_to_reverse);

    DWORD bytes_written;

    WriteFile(
        pipe_handle,
        (LPVOID)string_to_reverse,
        bytes_read,
        &bytes_written,
        NULL);
Run Code Online (Sandbox Code Playgroud)

客户端创建一个文件来使用管道,如下所示:

HANDLE pipe_handle = CreateFile(
    PIPE_REV_NAME,
    GENERIC_READ | GENERIC_WRITE,
    0,              // no sharing 
    NULL,           // default security attributes
    OPEN_EXISTING,  // opens existing pipe 
    0,              // default attributes 
    NULL
);
Run Code Online (Sandbox Code Playgroud)

并像这样读取和写入管道:

        strncpy_s(buff, toReverse.c_str(), MAX_PIPE_REVLEN - 1);

    printf("Sending: %s\n", buff);
    WriteFile(
        pipe_handle,
        (LPVOID)buff,
        toReverse.length(),
        &bytes_written,
        NULL);
    printf("Waiting\n");
    DWORD bytes_read = 0;
    ReadFile(
        pipe_handle,
        (LPVOID)buff,
        toReverse.length(),
        &bytes_read,
        NULL);
Run Code Online (Sandbox Code Playgroud)

客户端和服务器的输出

Lig*_*ica 5

这与管道无关。

从您的屏幕截图中我们可以看到,是您的客户端一次一个单词地处理您的输入。(注意每个单词如何重复“发送:”。)

您没有向我们展示该代码,或者实际上是一个最小的可重现示例,但我可以告诉您您做了这样的事情:

std::string input;
if (std::cin >> input)
{
   // send to pipe
}
Run Code Online (Sandbox Code Playgroud)

不。相反,请执行以下操作:

std::string input;
if (std::getline(std::cin, input))
{
   // send to pipe
}
Run Code Online (Sandbox Code Playgroud)

参考: