在Linux上使用C/C++中的write()函数通过UART Beaglebone Black写入70kB

using write() function in C/C++ on Linux to write 70kB via UART Beaglebone Black

本文关键字:函数 UART Beaglebone 70kB 写入 Black write Linux 中的 C++      更新时间:2023-10-16

我正试图通过Beaglebone Black上的UART编写一个图像。但当我在库中使用write()函数时。

int  write(int  handle, void *buffer, int nbyte);

不管nbyteint型,我都不能一次传输70kB。我显示了传输的字节数,结果是字节数=4111。

length = write(fd,body.c_str(),strlen(body.c_str())); // 
cout<<length<<endl; // result length = 4111;
cout<<strlen(body.c_str())<<endl; // result strlen(body.c_str()) = 72255;

我希望收到你的来信!

write调用不能确保您可以写入所提供的数据量,这就是为什么它是一个整数作为返回值,而不是布尔值。您看到的行为实际上在不同的操作系统中很常见,这可能是由于下划线设备可能没有足够的缓冲区或存储空间来写入70kb。你需要的是在一个循环中写入,每次写入都会写入未写入的数量:

int total = body.length(); // or strlen(body.c_str())
char *buffer = body.c_str();
int written = 0;
int ret;
while (written < total) {
    ret = write(fd, buffer + written, total - written);
    if (ret < 0) {
        // error
        break;
    }
    written += ret;
}