gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:59:52 25 4
gpt4 key购买 nike

我有一个似乎无法解决的问题:

我使用 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 并且可以运行一段时间。然后突然停止工作,过了一会儿又开始工作(所有这些都在同一个 session 中)。

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

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

结果始终等于strlen(string),因此我非常确定它的编写正确。谁能指出我正确的方向?

最佳答案

我不确定您想通过 tcflush(fd, TCOFLUSH); 实现什么目的。该函数调用专门丢弃 - 即放入垃圾桶 - 所有写入fd但尚未通过串行链路发送的数据。

引用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.

关于c - 串行通信 write() 并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com