
① 没有直接的对应,需要自己实现。
② 可以写c函数、汇编、或用第3方跨平台的函数库(比如ncurses)。下面是linux下c函数实现:
#include <stdio.h>#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
void changemode(int)
int kbhit(void)
int main(void)
{
int ch
changemode(1) /* 注意,打开mode */
while ( !kbhit() )
{
putchar('.')
}
ch = getchar()
printf("\nGot %c\n", ch)
changemode(0) /* 注意,关闭mode */
return 0
}
void changemode(int dir)
{
static struct termios oldt, newt
if ( dir == 1 )
{
tcgetattr( STDIN_FILENO, &oldt)
newt = oldt
newt.c_lflag &= ~( ICANON | ECHO )
tcsetattr( STDIN_FILENO, TCSANOW, &newt)
}
else
tcsetattr( STDIN_FILENO, TCSANOW, &oldt)
}
int kbhit (void)
{
struct timeval tv
fd_set rdfs
tv.tv_sec = 0
tv.tv_usec = 0
FD_ZERO(&rdfs)
FD_SET (STDIN_FILENO, &rdfs)
select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv)
return FD_ISSET(STDIN_FILENO, &rdfs)
}
---- 上述代码来自互联网。
在Unix/Linux下,并没有提供int kbhit(void)这个函数。在linux下开发控制台程序时,需要自己编写kbhit()实现的程序了。下面是kbhit在Unix/Linux下的一个实现。用到了一种终端 *** 作库termios。下面是头文件kbhit.h:QUOTE:#ifndef KBHITh#define KBHIThvoid init_keyboard(void)void close_keyboard(void)int kbhit(void)int readch(void)#endif下面式源程序kbhit.c:QUOTE:#include "kbhit.h"#include <stdio.h>#include <termios.h>static struct termios initial_settings, new_settingsstatic int peek_character = -1void init_keyboard(){tcgetattr(0,&initial_settings)new_settings = initial_settingsnew_settings.c_lflag &= ~ICANONnew_settings.c_lflag &= ~ECHOnew_settings.c_lflag &= ~ISIGnew_settings.c_cc[VMIN] = 1new_settings.c_cc[VTIME] = 0tcsetattr(0, TCSANOW, &new_settings)}void close_keyboard(){tcsetattr(0, TCSANOW, &initial_settings)}int kbhit(){unsigned char chint nreadif (peek_character != -1) return 1new_settings.c_cc[VMIN]=0tcsetattr(0, TCSANOW, &new_settings)nread = read(0,&ch,1)new_settings.c_cc[VMIN]=1tcsetattr(0, TCSANOW, &new_settings)if(nread == 1) {peek_character = chreturn 1}return 0}int readch(){char chif(peek_character != -1) {ch = peek_characterpeek_character = -1return ch}read(0,&ch,1)return ch}这个问题,你研究一下kbhit函数的源码就知道了,搜kbhit.c linux ,我找到了这个代码注意看,里面有select这一句,
status = select(0 + 1, &read_handles, NULL, NULL, &timeout)
这一句就是实现一个定时返回的功能,调用select的时候,系统监控read_handles,如果有变化,返回一个正数,时间到,没有变化返回0,错误返回负数。
你也可以用select函数去实现别的定时返回功能,这个在网络编程里很常用。网络编程里很多时候都采用select来做超时等待,一个网络请求发出去了,如果对方在一段时间内没有,就超时返回。
static int kbhit(void)
{
struct timeval timeout
fd_set read_handles
int status
raw()
/* check stdin (fd 0) for activity */
FD_ZERO(&read_handles)
FD_SET(0, &read_handles)/* 设置fd为标准输入 */
timeout.tv_sec = 1 /* 设置超时时间为1秒 */
timeout.tv_usec = 0
status = select(0 + 1, &read_handles, NULL, NULL, &timeout)
if(status <0)
{
printf("select() failed in kbhit()\n")
exit(1)
}
return status
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)