键盘中断输入测试程序

今天测试需要写一个接收键盘键的中断输入就停止,再按就继续,亲测有效,程序如下:
#include <stdio.h>
#include “conio.h”
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}

int main()
{
char i;int y=0;
while(1)
{
if(!(kbhit()))
{
y=0;
printf(“key is not pressed\n”);
//do something
}
else
{
printf(“key pressed , press again to resume\n”);
i=getch();
y=1;
}
if(y==1)
{
getch();
}
}
return 0;
}

上面程序需要注意的的是kbhit()非linux标准库函数,需要加头文件conio.h,这个头文件需要下载,下面把这个头文件内容贴出来:
#include <termios.h>
#include <stdio.h>

static struct termios old, new;

/* Initialize new terminal i/o settings /
void initTermios(int echo)
{
tcgetattr(0, &old); /
grab old terminal i/o settings /
new = old; /
make new settings same as old settings /
new.c_lflag &= ~ICANON; /
disable buffered i/o /
new.c_lflag &= echo ? ECHO : ~ECHO; /
set echo mode /
tcsetattr(0, TCSANOW, &new); /
use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}

/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}

/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}

/* Let’s test it out */

把这个头文件放到linux 如ubuntu下/usr/include/下即可;

Ubuntu下编译:
gcc -o test test.c

执行:
key is not pressed
key is not pressed
key is not pressed
key is not pressed
key is not pressed
key is not pressed
key pressed (execution pause) , press again to resume
按下键盘即可接收停止和继续