在 C 中获取键盘中断 [英] Get Keyboard Interrupt in C

查看:22
本文介绍了在 C 中获取键盘中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序:

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

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

The above program stops when the time reaches 0. My requirement is during the runtime of the program, If I press any key like spacebar or any other key, the program gets paused and once again I press the key, the program gets resumed. So for doing this, before execution of while condition, we submit the signal handler for keyboard interrupt. In C how to do this.

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

What is the function used to get keyboard interrupt. I dont want to get input from the user, I want to handle the interrupt generated by the user through keyboard.

在此先感谢..,

推荐答案

纯标准 C99 或 C11 中不存在键盘(stdin 不是键盘,可能是 pipe(7) 所以并不总是 tty(4); 你可以从 /dev/tty ...).

The keyboard does not exist in purely standard C99 or C11 (stdin is not a keyboard, and could be a pipe(7) so is not always a tty(4); you might read from /dev/tty ...).

因此,它不像您想要的那样简单,而且它是特定于操作系统的.我专注于 Linux.

So it is much less simple that what you want it to be, and it is operating system specific. I am focusing on Linux.

阅读更多关于 ttys 的信息,特别是阅读 tty demystified.请注意,tty 通常处于熟化模式,其中 kernel 正在缓冲行(除了 stdin 正在缓冲行).

Read much more about ttys, notably read the tty demystified. Notice that tty are usually in cooked mode, where the kernel is buffering lines (in addition of stdin being line buffered).

合理的方法是使用终端库,如 ncursesreadline.这些库将 tty 设置为原始模式(您可以自己执行此操作,请参阅 thistermios(3);您可能还需要 poll(2)).退出前一定要正确退出并将tty重置为cooked模式.

The reasonable way is to use a terminal library like ncurses or readline. These libraries are setting the tty in raw mode (which you might do by yourself, see this and termios(3); you'll probably need also to poll(2)). Be sure to exit properly and reset the tty to cooked mode before exiting.

但是你的生命可能太短了,无法潜入 termios(3)tty_ioctl(4) 就这样使用 ncursesreadline

But your life is probably too short to dive into termios(3) and tty_ioctl(4) so just use ncurses or readline

你也可以考虑一些 GUI 应用程序(例如上面的 X11Wayland).然后使用工具包(GTK, Qt, ...).

You could also consider some GUI application (e.g. above X11 or Wayland). Then use a toolkit (GTK, Qt, ...).

这篇关于在 C 中获取键盘中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆