C 串行通信读取()错误

C 串行通信读取()错误,c,linux,serial-port,C,Linux,Serial Port,这对知情人士来说应该相当简单,但我已经挣扎了一段时间,希望能有一些想法。我正在编写一个从串行通信端口读取数据的应用程序 我的设置: 我有一台打开putty的windows机器,并连接到我感兴趣的通讯端口。 我有一台linux ubuntu机器,我正在其中用C编写这个软件。 我在windows机器上输入putty,并尝试在linux机器上用我的应用程序读取它 我所拥有的: 到目前为止,使用下面的代码,我可以从linux计算机上的应用程序成功地写入windows计算机上的putty显示,但在wind

这对知情人士来说应该相当简单,但我已经挣扎了一段时间,希望能有一些想法。我正在编写一个从串行通信端口读取数据的应用程序

我的设置:

我有一台打开putty的windows机器,并连接到我感兴趣的通讯端口。 我有一台linux ubuntu机器,我正在其中用C编写这个软件。 我在windows机器上输入putty,并尝试在linux机器上用我的应用程序读取它

我所拥有的:

到目前为止,使用下面的代码,我可以从linux计算机上的应用程序成功地写入windows计算机上的putty显示,但在windows计算机上键入时,我无法读取linux计算机上的缓冲区

代码:

有人对可能发生的事情有什么想法吗?read命令返回-1错误


谢谢

您可能忘记了一些Linux或Posix标记。你的问题肯定是操作系统特有的!在Linux上,当Read -Read 1失败时,您应该考虑ErnNO,例如使用PrRoRy感谢来提示它,它所给出的错误是暂时不可用的资源,将考虑您应该阅读并考虑使用一些复用系统,如巴西尔已经指出的,尤其是用于读取。错误检查和日志记录对于成功调试至关重要。您应该对所有系统调用执行此操作。
#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>

int openport()
{
    int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY | O_NONBLOCK );
    struct termios tty;
    struct termios tty_old;
    memset(&tty, 0, sizeof tty);

    /* Error Handling */
    if ( tcgetattr( USB, &tty ) != 0 )
    {
        printf("Error 1, or something");
    }

    /* Save old tty parameters */
    tty_old = tty;

    /* Set Baud Rate */
    cfsetospeed (&tty, (speed_t)B9600);
    cfsetispeed (&tty, (speed_t)B9600);

    /* Setting other Port Stuff */
    tty.c_cflag     &=  ~PARENB;        // Make 8n1
    tty.c_cflag     &=  ~CSTOPB;
    tty.c_cflag     &=  ~CSIZE;
    tty.c_cflag     |=  CS8;

    tty.c_cflag     &=  ~CRTSCTS;       // no flow control
    tty.c_cc[VMIN]      =   1;                  // read doesn't block
    tty.c_cc[VTIME]     =   5;                  // 0.5 seconds read timeout
    tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

    /* Make raw */
    cfmakeraw(&tty);
    /* Flush Port, then applies attributes */
    tcflush( USB, TCIFLUSH );
    if ( tcsetattr ( USB, TCSANOW, &tty ) != 0)
    {
        printf("Error, or something");
    }

    return USB;
}

int main()
{
    int n = 0;
    int j = 0;
    unsigned char buf[10] = {0,0,0,0,0,0,0,0,0,0};
    printf("Hello world!\n");

    int USB = openport();


    unsigned char cmd[] = "INIT Hey SHanahas \r";
    int n_written = 0;

    do 
    {
        n_written += write( USB, &cmd[n_written], 1 );
    }
    while (cmd[n_written-1] != '\r' && n_written > 0);

    printf("Here\n\n");


    do
    {
        n = read( USB, &buf, 1 );
        printf("%s \n",buf);
        printf("%d",n);
    }
    while( buf != '\r' && n > 0);



    printf("Herr2");

    return 0;
}