#include #include #include #include #include #include #include #include #include #define BUFFER_SIZE 1024 int mode = 0; int fd = 0; int thread_run = 1; void print_usage(const char *prog_name) { printf("%s 1 /dev/cashd0\n", prog_name); printf("%s 0 /dev/cashd0\n", prog_name); } int set_nonblocking(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { perror("fcntl F_GETFL"); return -1; } if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { perror("fcntl F_SETFL"); return -1; } return 0; } int set_blocking(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { perror("fcntl F_GETFL"); return -1; } if (fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) == -1) { perror("fcntl F_SETFL"); return -1; } return 0; } void blocking_read(int fd) { fd_set read_fds; struct timeval tv; char buffer[BUFFER_SIZE]; int ret; printf("wait data...\n"); while (thread_run) { FD_ZERO(&read_fds); FD_SET(fd, &read_fds); tv.tv_sec = 1; tv.tv_usec = 0; ret = select(fd + 1, &read_fds, NULL, NULL, &tv); if (ret == -1) { if (errno == EINTR) { continue; } perror("select error"); break; } if (FD_ISSET(fd, &read_fds)) { memset(buffer, 0, sizeof(buffer)); ssize_t n = read(fd, buffer, sizeof(buffer) - 1); if (n > 0) { buffer[n] = '\0'; printf("read %zd byte: %s\n", n, buffer); if (strncmp(buffer, "quit", 4) == 0 || strncmp(buffer, "exit", 4) == 0) { printf("exit\n"); break; } } else if (n == 0) { printf("close\n"); break; } else { if (errno != EAGAIN && errno != EWOULDBLOCK) { perror("read error"); break; } } } } } void nonblocking_read(int fd) { fd_set read_fds; struct timeval timeout; char buffer[BUFFER_SIZE]; int ret; while (thread_run) { memset(buffer, 0, sizeof(buffer)); ssize_t n = read(fd, buffer, sizeof(buffer) - 1); if (n > 0) { printf("read %zd byte: %s\n", n, buffer); } sleep(1); } } void *read_pthread_func(void *arg) { if (mode == 0) { if (set_nonblocking(fd) < 0) { return NULL; } nonblocking_read(fd); } else { if (set_blocking(fd) < 0) { return NULL; } blocking_read(fd); } } int main(int argc, char *argv[]) { const char *device_path; int open_flags; int ret = 0; char cmd = 0; pthread_t read_thread = 0; if (argc != 3) { print_usage(argv[0]); return 1; } mode = atoi(argv[1]); if (mode != 0 && mode != 1) { print_usage(argv[0]); return 1; } device_path = argv[2]; open_flags = O_RDWR; fd = open(device_path, open_flags); if (fd < 0) { perror("open fail:"); return 1; } pthread_create(&read_thread, NULL, read_pthread_func, NULL); while(1) { printf("please input cmd: o/O-open q-quit\n"); scanf(" %c", &cmd); if (cmd == 'o' || cmd == 'O') { ret = write(fd, &cmd, 1); if (ret < 0) { perror("write fail:"); break; } } else if( cmd == 'q') { break; } else { printf("input error\n"); } } thread_run = 0; pthread_join(read_thread, NULL); close(fd); return 0; }