Linux select/poll机制原理分析( 三 )

3.2 测试代码测试代码逻辑:

  1. 创建一个设值线程,用于每隔2秒来设置一次count值;
  2. 主线程调用select函数监听,当设值线程设置了count值后,select便会返回;
#include <stdio.h>#include <string.h>#include <fcntl.h>#include <pthread.h>#include <errno.h>#include <unistd.h>#include <sys/ioctl.h>#include <sys/stat.h>#include <sys/types.h>#include <sys/time.h>static void *set_count_thread(void *arg){ int fd = *(int *)arg; unsigned int count_value = https://www.isolves.com/it/rj/czxt/linux/2020-10-10/1; int loop_cnt = 20; int ret; while (loop_cnt--) {ret = ioctl(fd, NOTIFY_SET_COUNT, &count_value);if (ret < 0) {printf("ioctl set count value fail:%sn", strerror(errno));return NULL;}sleep(1); } return NULL;}int main(void){ int fd; int ret; pthread_t setcnt_tid; int loop_cnt = 20; /* for select use */ fd_set rfds; struct timeval tv; fd = open("/dev/poll", O_RDWR); if (fd < 0) {printf("/dev/poll open failed: %sn", strerror(errno));return -1; } /* wait up to five seconds */ tv.tv_sec = 5; tv.tv_usec = 0; ret = pthread_create(&setcnt_tid, NULL,set_count_thread, &fd); if (ret < 0) {printf("set_count_thread create fail: %dn", ret);return -1; } while (loop_cnt--) {FD_ZERO(&rfds);FD_SET(fd, &rfds);ret = select(fd + 1, &rfds, NULL, NULL, &tv);//ret = select(fd + 1, &rfds, NULL, NULL, NULL);if (ret == -1) {perror("select()");break;}else if (ret)printf("Data is available now.n");else {printf("No data within five seconds.n");} } ret = pthread_join(setcnt_tid, NULL); if (ret < 0) {printf("set_count_thread join fail.n");return -1; } close(fd); return 0;}



推荐阅读