您需要conio.h来满足您的需求。它定义了kbhit()和getch()两者都等待来自键盘的输入。
每当调用kbhit()时,它都会检查键盘缓冲区,并在缓冲区有任何按键时返回非零值,否则返回0。
conio.h由MSDOS编译器使用,不是标准C库(ISO)的一部分。它在POSIX中也没有定义。
#include<stdio.h>
#include<conio.h>
int main()
{
while(1)
{
while(!kbhit())
{
//works continuously until interrupted by keyboard input.
printf("M Tired. Break Me\n");
}
getch();
}
return 0;
}
对于Linux,您可以使用下面的代码片段来实现的kbhit()通过使用来自fnctl.h fnctl()信号处理:
#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;
}
什么操作系统? – kaylum
Ubuntu 12.04 lts – mrg
使用sighandler_t信号(int signum,sighandler_t handler); – venki