#include #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "usage: reader tty-device\r\n"); return 1; } int fd; struct termios tty; memset(&tty, 0, sizeof(tty)); fd = open(argv[1], O_RDWR); if (fd <= 0) { err(1, "open %s", argv[1]); } if (tcgetattr(fd, &tty) != 0) { err(1, "tcgetattr"); } tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common) tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common) tty.c_cflag |= CS8; // 8 bits per byte (most common) tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common) tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1) tty.c_lflag &= ~ICANON; tty.c_lflag &= ~ECHO; // Disable echo tty.c_lflag &= ~ECHOE; // Disable erasure tty.c_lflag &= ~ECHONL; // Disable new-line echo tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes tty.c_oflag &= ~OPOST; tty.c_oflag &= ~ONLCR; tty.c_cc[VTIME] = 0; // non-blocking tty.c_cc[VMIN] = 0; cfsetispeed(&tty, B115200); cfsetospeed(&tty, B115200); if (tcsetattr(fd, TCSANOW, &tty) != 0) { err(1, "tcsetattr"); } char data[100] = { 0 }; if (write(fd, "test\n", 5) < 0) { err(1, "write"); } while (1) { struct pollfd ufds; ufds.fd = fd; ufds.events = POLLIN; int rc = poll(&ufds, 1, 0); if (rc < 0) { err(1, "poll"); } if (rc == 0) { // timeout continue; } if (ufds.revents & POLLIN) { ssize_t r = read(ufds.fd, data, sizeof(data)); if (r == -1) { err(1, "read"); } if (rc > 0) { printf("read %d bytes\n"); } } } }