reading from serial port in c breaks up lines

后端 未结 2 1477
眼角桃花
眼角桃花 2021-01-26 13:37

I\'m trying to write a little program in C that will read from the serial port using the select command so that it blocks and waits for input. It\'s working, except it keeps br

2条回答
  •  终归单人心
    2021-01-26 14:19

    The problem is that you are reading an arbitrary number of bytes, and then outputing them separated by a newline:

    read(fileDescriptor, buf, 1000);
    printf("%s\n", buf);
    

    You opened the descriptor O_NONBLOCK and I'm not sure your fcntl call is sufficient to clear it. The result is that read pulls out however many characters happen to be buffered that that moment, and then you print them followed by a newline.

    You probably do not want to read in blocking mode, as then it may not return until 1000 characters are read. This may be closer to what you want:

    amt = read(fileDescriptor, buf, 1000);
    if (amt > 0)
        write(1,buff,amt);
    else
        break;
    

    Of course, there should be a lot more error handling.

提交回复
热议问题