select函数的用法

实例1:监听标准输入

#include <stdio.h>
#include <string.h>
#include <sys/select.h>

#define STDIN 0

int main()
{
	int  n, flag;
	char buf[80];
	fd_set fds;
	struct timeval tv;
	int fd = STDIN;

	printf("type \"eXit\" to exit.\n");

	flag = 1;
	while(1 == flag)
	{
		tv.tv_sec=10;
		tv.tv_usec=0;
		FD_ZERO(&fds);
		FD_SET(fd,&fds);

		switch(select(fd+1, &fds, NULL, NULL, &tv))
		{
		case -1:  // select错误
			printf("返回错误。\n");
			flag = -1;
			break;
		case 0: //再次轮询
			printf("超时。\n");
			break;
		default:
			if(FD_ISSET(fd, &fds)) 
			{
				fgets(buf, 20, stdin);

				n = strlen(buf);
				if('\n' == buf[n-1])
					buf[n-1] = '\0';
				printf("数据:%s\n", buf);

				if(0 == strcmp(buf, "eXit")) //退出程序?
				{
					flag = 0;
					break;
				}
				
			}
			break;
		}
	}

	return flag;
}

运行结果示例:

# ./select
type "eXit" to exit.
da
数据:da
wert
数据:wert
超时。
超时。
eXit
数据:eXit
#


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值