为什么忽略我的缓冲区长度?

Nit*_*Nit 10 c uart

我正在开发一个小型硬件项目的接收器.我正在使用UART传输数据的小板.
接收器代码如下所示,我将在短期内单独解释有问题的位.

#define TTY "/dev/ttys002"

#include <stdio.h>
#include <string.h>
#include <unistd.h> //Unix standard functions
#include <fcntl.h> //File controls
#include <errno.h> //Error numbers
#include <assert.h>
#include <termios.h> //Posix terminal

int open_port(const char * tty) {
    int fd;
    fd = open(tty, (O_RDWR | O_NOCTTY | O_NDELAY));
    assert("__failed to open port__" && fd != -1);
    //Block until read
    fcntl(fd, F_SETFL, 0);
    return fd;
}

void configure_port(int fd) {
    struct termios options;
    //Get current options
    tcgetattr(fd, &options);

    //9600 Baud
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);

    //Receive & local mode
    options.c_cflag |= (CLOCAL | CREAD);

    //Raw output
    options.c_oflag &= ~OPOST;

    //No hardware flow control
    options.c_cflag &= ~CRTSCTS;

    //No parity, 1 stop bit
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;

    //8 data bits
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    //Write options back, set them immediately
    tcsetattr(fd, TCSANOW, &options);
}

int main(int argc, const char * argv[]) {
    int fd = open_port(TTY);
    const size_t count = 8;
    char buf[count + 1];
    ssize_t n;
    configure_port(fd);
    while (1) {
        n = read(fd, buf, count);
        buf[count] = '\0';
        if (n > 0) {
            printf("%s\n", buf);
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于我目前没有我的硬件,所以我决定在常规的tty(#define TTY "/dev/ttys002")上测试我的接收器.为了测试它,我只是编译并运行上面的代码,然后打开一个单独的终端并:

echo "text" >> /dev/ttys002
Run Code Online (Sandbox Code Playgroud)

所有这一切都运行良好,我得到了所有我正在回应的数据.

但是,当我在tty中输入一条长消息时会出现问题:

echo "this is a longer test message" >> /dev/ttys002
Run Code Online (Sandbox Code Playgroud)

我在程序输出中将整个消息作为单个字符串接收.为什么会这样?我原本期望将文本分成8个字符(const size_t count = 8;)的块.

如果它很重要,我将使用本指南作为配置的首选.

编辑:请参阅评论以进一步讨论该问题.

Ser*_*sta 1

恕我直言,您的消息分成八个字符的块:n = read(fd, buf, count);一次不能给出超过 count 个字节。

但由于您没有在 RAW 模式下配置 tty 线路,因此仍然处于行缓冲模式。因此,底层驱动程序会阻止第一次读取,直到它有一个以 a 结尾的整行\n(或超过缓冲区容量)。

然后读取返回前 8 个字节,下一个读取也立即返回 8 个字节,因为数据在驱动程序缓冲区中可用。

如果您想使用原始输入模式,您应该在man termios中查看非规范模式:

options.c_cflags &= ~ICANON;
/* optionally if defaults are not appropriates */
options.c_cc[VMIN] = vmin; /* default is 1 */
options.c_cc[VTIME] = vtime; /* default is 0 */
Run Code Online (Sandbox Code Playgroud)

但无论如何,您读取字符并不会添加终止 null,因此 buf 没有理由以 null 终止。您应该只打印实际读取的字符数:

const size_t count = 8;
char buf[count];
ssize_t n;
configure_port(fd);
while (1) {
    n = read(fd, buf, count);
    if (n > 0) {
        printf("%.*s\n", n, buf); /* only print the n characters */
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,但是 `printf("%s\n", buf);` 必须打印分成不同行的 8 个字符长度的字符串。这是对的吗?问题是空终止。 (2认同)