在C中获取键盘中断

时间:2015-09-04 05:21:14

标签: c linux unix keyboard signal-handling

程序:

#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中如何做到这一点。

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

先谢谢你,

3 个答案:

答案 0 :(得分:3)

键盘在纯标准C99或C11中不存在( stdin 不是键盘,可能是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,...)。

答案 1 :(得分:0)

我的要求是在程序运行期间,如果我按任意键,如空格键或任何其他键,程序将暂停,再次按下该键,程序将恢复。 < / p>

您可以使用此类代码实现此目的

#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;
}

答案 2 :(得分: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;
        }