selectOutOfTime.c
里边的代码如下:
#include<stdio.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
#include <string.h>#define BUF_SIZE 100int main(void){fd_set reads;struct timeval tv;int errorNum;char send_line[BUF_SIZE];FD_ZERO(&reads);FD_SET(0,&reads);tv.tv_sec = 5;tv.tv_usec = 0;errorNum = select(1,&reads,NULL,NULL,&tv);// 原先以为第一个参数中,0 代表标准输入,1代表标准输出,这是错误的想法if (FD_ISSET(STDIN_FILENO, &reads)) {if (fgets(send_line, BUF_SIZE, stdin) != NULL) {int i = strlen(send_line);if (send_line[i - 1] == '\n') {send_line[i - 1] = 0;}printf("input string: %s\n", send_line);}}if(errorNum == -1){perror("select()");}else if(errorNum){printf("Data is available now.\n");}else{//此处就是当errorNum = 0时,表明超时了printf("No data within five seconds.\n");}return 0;
}
可以看到这是一个简单的定时小程序,若是5秒内没有输入字符串,那么就会输出No data within five seconds.
,然后程序退出;要是5
秒内输入字符串了,那么就会先把input string:
+刚刚输入的字符串输出到屏幕上,之后再输出Data is available now.
,然后结束程序。
sudo gcc selectOutOfTime.c -o selectOutOfTime
进行编译,sudo ./selectOutOfTime
两次执行,对应上边的5秒内是否输出字符串的描述。
进行一下改动,就可以实现定时任务了,selectOutOfTimeWhile.c
代码如下:
#include<stdio.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
#include <string.h>#define BUF_SIZE 100int main(void){fd_set reads, cpy_reads;struct timeval tv;int errorNum;char send_line[BUF_SIZE];FD_ZERO(&reads);FD_SET(0,&reads);while(1){cpy_reads=reads;tv.tv_sec = 5;tv.tv_usec = 0;errorNum = select(1,&cpy_reads,NULL,NULL,&tv);if (FD_ISSET(STDIN_FILENO, &cpy_reads)) {FD_CLR(STDIN_FILENO, &cpy_reads);if (fgets(send_line, BUF_SIZE, stdin) != NULL) {int i = strlen(send_line);if (send_line[i - 1] == '\n') {send_line[i - 1] = 0;}printf("input string: %s\n", send_line);}}if(errorNum == -1){perror("select()");}else if(errorNum){printf("Data is available now.\n");}else{printf("No data within five seconds.\n");}}return 0;
}
sudo gcc selectOutOfTimeWhile.c -o selectOutOfTimeWhile
进行编译,sudo ./selectOutOfTimeWhile
执行,之后可以看到若是没有输入内容的话,那么就会每隔5
秒输出No data within five seconds.
,最后按下Ctrl+c退出程序。
此文章为11月Day 14学习笔记,内容来源于极客时间《网络编程实战》。