我正在尝试使用c编程在linux上读/写串行数据 . 我可以成功打开端口并设置属性 . 但是当我尝试读取串行数据时, read() 系统调用无限期地等待 . 无法理解为什么会这样 .

为了测试串行通信,我使用的是具有9600波特和8N1配置的arduino .

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>

int init(char *port);
void reads(int fd);

int main(int argc, char *argv[]){
    int fd;

    fd = init(argv[1]);

    fprintf(stdout, "\n\n####### DATA ########\n\n");
    reads(fd);

    close(fd);

    return EXIT_SUCCESS;
}

int init(char *port){
    int fd;
    struct termios topt;

    fd = open(port, O_RDWR | O_NONBLOCK);
    if(fd < 0){
        fprintf(stderr, "init error: can't open port %s\n!", port);
        exit(1);
    }

    if(tcgetattr(fd, &topt) < 0){
        fprintf(stderr, "init error: can't get terios attributes!\n");
        exit(1);
    }

    topt.c_cflag &= ~CRTSCTS;
    topt.c_cflag |= CREAD | CLOCAL;
    topt.c_cflag &= ~(IXON | IXOFF | IXANY);
    topt.c_cflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    topt.c_cflag &= ~OPOST;

    cfsetispeed(&topt, B9600);
    cfsetospeed(&topt, B9600);

    topt.c_cflag &= ~PARENB;
    topt.c_cflag &= ~CSTOPB;
    topt.c_cflag &= ~CSIZE;
    topt.c_cflag |= CS8;

    topt.c_cc[VMIN] = 1;
    topt.c_cc[VTIME] = 0;

    tcsetattr(fd, TCSANOW, &topt);
    if(tcsetattr(fd, TCSAFLUSH, &topt) < 0){
        fprintf(stderr, "init error: can't set attributes!\n");
        exit(1);
    }
}

void reads(int fd){
    char rdbuff[1];

    while(read(fd, rdbuff, 1) > 0){
        fprintf(stdout, "%c", rdbuff[0]);
    }
}

谢谢!