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

标签 c++ operating-system pipe

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

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

HANDLE pipe_handle = CreateNamedPipe( PIPE_REV_NAME,//名称 PIPE_ACCESS_DUPLEX,//开启模式 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,//管道模式 1,//最大实例数 1024,//输出缓冲区大小 1024,//输入缓冲区大小 NMPWAIT_USE_DEFAULT_WAIT, 空);

然后像这样在服务器上读写它:

    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);

客户端像这样创建一个文件来使用管道:

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
);

然后像这样读写管道:

        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);

The Output of the client and server

最佳答案

这与管道无关。

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

您没有向我们展示该代码,也没有向我们展示一个最小的可重现示例,但我可以看出您做了这样的事情:

std::string input;
if (std::cin >> input)
{
   // send to pipe
}

不要。相反,这样做:

std::string input;
if (std::getline(std::cin, input))
{
   // send to pipe
}

引用资料:

关于c++ - 为什么我的 NamedPipe 用空格分隔我的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57099262/

相关文章:

c++ - 可变参数模板类的可变参数模板

c++ - C++生命周期延长的问题

linux - 文件系统信息如何存储?

java - 如何在 Linux 中使用 C 或 Java 获取硬盘的序列号 id?

c - 将子进程的返回值接收到父进程中?

javascript - 如何为 gulp 编写管道序列?

c++ - 在 C++11 中,如何不向线程传递参数?

c++ - 什么是 g++-3/gcc-3?

audio - 有没有一种方法可以为带有两个音频输出的CPU中的特定程序选择音频端口?

python - 如何使用带有 python 子进程模块或 gst-launch-1.0 命令的 gstreamer 接收字节流?