首页 > 解决方案 > Windows 进程间通信 (IPC)(命名管道)- 从属程序自随机时间以来未收到任何数据

问题描述

我有一个主机程序(A)和一个从属程序(B),A定期(大约每0.5秒)向B发送一些数据(作为命令),而B接收来自A的命令,它会做一些相应的事情。

一开始一切正常,但过了一段时间,可能是 3 分钟或 5 分钟后,在随机时间,B 不再接收新命令,但 A 仍在发送新命令。

我通过编写一些文本日志来检查 A 和 B 的状态,日志如下所示:

<< 发送了什么 >> 命令 1 命令 2 命令 3 ... 命令 70 ... 命令 100

<< B 收到的内容>> Command 1 Command 2 Command 3 ... Command 70(到此为止,71~100 不见了)


Host程序的核心部分(一):

...
HANDLE host_to_slave;
DWORD host_to_slave_buffer_index;
...

for(int i = 0; i < 1000; i++)
{
    ...
    std::string temp_string = "S/1.234567/9.876543"/";
    const char *command_str = temp_string.c_str();
    WriteFile(host_to_slave,
        command_str,
        temp_string.length(),
        &host_to_slave_buffer_index,
        NULL);
    Sleep(300); // Wait for some hardware.

    // Here write temp_string (command sent to B) to the log file.
    ...
}
...

从机程序的核心部分(B):

...
HANDLE host_to_slave;
char host_to_slave_buffer[1024];
DWORD host_to_slave_buffer_index;
...

while(true) // Infinite checking loop
{
    ...
    ReadFile(host_to_slave,
        host_to_slave_buffer,
        sizeof(host_to_slave_buffer) - 1,
        &host_to_slave_buffer_index,
        NULL);
    host_to_slave_buffer[host_to_slave_buffer_index] = '\0';

    if (host_to_slave_buffer[0] != '\0')
    {
        ...
        // Here write host_to_slave_buffer[] (command from A) to the log file.
        ...
    }
    ...
    Sleep(10); // The minimum period of infinite checking loop.
}

B 只是检查是否永远有来自 A 的任何新命令并执行相应的操作。我只是无法弄清楚为什么它自“随机”时间以来没有收到任何命令。例如,B的日志卡在Command 70,有时是Command 30,Command 90。但是A的日志总是按预期运行-一直发送命令直到最新的命令,与Windows操作系统有什么关系?

标签: visual-c++

解决方案


推荐阅读