串行通信 write() 并不总是有效

serial communication write() doesn't work always

我有一个我似乎无法弄清楚的问题:

我使用 Putty 在 RPi 和我的 PC 之间通过蓝牙进行串行通信。 我使用以下代码将文本从我的 RPi 发送到 Putty:

ssize_t serial::writeSerialPort(char const *string)
{
    /*
     write a string to the serial connection
     */

    ssize_t result = write(fd, string, strlen(string));

    tcflush(fd, TCOFLUSH);
    if (result != strlen(string))
        printf("Failed to write to serial port!\n");
    else
        printf("Wrote to serial port!\n");

    return result;
}

现在奇怪的是,有时文本会被发送到 Putty 并且可以工作一段时间。 然后突然停止工作,过了一会儿又开始工作(都在同一个会话中)。

当我设置断点并调试我的代码时,文本总是在 write() 函数之后(在 tcflush() 之前)输出。

这当然让我很难找出为什么我有这个 "bug"。

结果总是等于 strlen(string) 所以我很确定它是正确的。 谁能给我指出正确的方向?

我不确定你想通过 tcflush(fd, TCOFLUSH); 实现什么。该函数调用具体 discards - 即放入垃圾桶 - 所有写入 fd 但尚未通过串行 link 发送的数据。

引用 Linux manuals:

tcflush() discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of queue_selector:

  • TCOFLUSH

    flushes data written but not transmitted.


也许您想改用 tcdrain()

tcdrain() waits until all output written to the object referred to by fd has been transmitted.