2015-09-04 61 views
1

计划:获取键盘中断用C

#include<stdio.h> 
void main() 
{ 
    int time=1800; 
    while(1){ 
     system("clear"); 
     time-=1; 
     printf("%d\n",time); 
     sleep(1); 
    if(time==0) 
     pause(); 
    } 
} 

当时间达到0.我的要求是该程序的运行过程中,如果我按空格键一样或任何其他键任意键上面的程序停止,程序会暂停,再次按下该键,程序会恢复。所以为此,在条件执行 之前,我们提交键盘中断的信号处理程序。在C如何做到这一点。

什么是用于获取键盘中断的函数。我不想从用户那里得到输入,我想通过键盘处理用户产生的中断。

在此先感谢..,

+0

什么操作系统? – kaylum

+0

Ubuntu 12.04 lts – mrg

+1

使用sighandler_t信号(int signum,sighandler_t handler); – venki

回答

0

我的要求是该程序的运行过程中,如果我按空格键一样或任何其他键任意键,该程序被暂停,并再次我按下键,程序得到恢复。

您可以使用此类型的代码实现这个

#include <stdio.h> 
int main() 
{ 
    char i;int y=0; 
    while(1) 
    { 
    if(!(_kbhit())) 
    { 
     y=0; 
     printf("//key is not pressed"); 
     //do what you want 
    } 
    else 
    { 
     printf("key pressed (execution pause) , press again to resume"); 
     i=_getch(); 
     y=1; 
    } 
    if(y==1) 
    { 
     getch(); 
    } 
    } 
    return 0; 
} 
+0

_kbhit(),_getch()在哪里声明它的意思在哪些头文件中声明这些头文件 – mrg

+0

@mohan header是'conio.h' – ameyCU

+1

@ameyCU conio.h仅在Windows上可用。 Iam使用Ubuntu 12.04 – mrg

2

键盘不纯粹的标准C99或C11存在(标准输入不是一个键盘,并可能是一个pipe(7)所以并不总是一个tty(4);你可能会从/dev/tty ......)读取。

因此,它要简单得多,而且是特定于操作系统的。我专注于Linux。

阅读更多关于ttys的信息,特别是阅读tty demystified。请注意,tty通常处于熟化模式,其中内核为缓冲行(此外还有stdin为行缓冲)。

合理的方法是使用像ncursesreadline这样的终端库。这些库正在设置原始模式下的tty(您可以自己完成,参见thistermios(3);您可能还需要poll(2))。确保在退出前正确退出并将tty重置为已煮熟模式。

但你的生活可能是太短暂潜入termios(3)tty_ioctl(4)因此就使用ncursesreadline

你也可以考虑一些GUI应用程序(例如高于X11Wayland)。然后使用工具包(GTKQt,...)。

0

您需要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; 
     }