如何在不停止C程序的情况下获取最后按下的键?

发布于 2024-08-06 18:44:30 字数 117 浏览 10 评论 0原文

使用命令行界面编写应用程序,我想随时知道是否按下了 F1 或 ESC 或箭头键。做到这一点最简单的方法是什么?我想避免使用 readline 类型库。

这是一个 Linux 特定问题;该程序不是多线程的。

Writing an application with command line interface and I would like to know at any time if F1 or ESC or an arrow key is pressed. What is the simplest way of doing this? I would like to avoid using a readline type library.

This is a Linux specific question; the program is not multithreaded.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暮色兮凉城 2024-08-13 18:44:30

在 C 标准中没有办法做到这一点,但各种操作系统上的 C 实现通常有一些扩展来做到这一点。

在 Windows 上,您可以使用 getch()。在 Linux 和 Unix 上,看看这个问题:

非阻塞 getch(), ncurses

另外,这是 C 常见问题解答列表中“系统依赖关系”部分的第一个问题:

19.1

There is no way to do this in the C standard, but C implementations on various operating systems usually have some extension to do this.

On Windows, you can use getch(). On Linux and Unix, look at this question:

Non-blocking getch(), ncurses

Also, this is the very first question in the "System Dependencies" section in the C FAQ list:

19.1

美人迟暮 2024-08-13 18:44:30

Linux 编程入门中介绍了适用于 Linux 的 kbhit() 实现第 167 页。您可以通过提供的链接在线阅读。

编辑:我提到 kbhit() 是因为它是在明确问题与 Linux 相关之前作为解决方案发布的。不幸的是,该解决方案已被删除,这很不幸。原理是,当 kbhit() 返回非零时,后续的面向字符的阻塞读取调用将不会阻塞。这仅适用于面向字符的输入; getchar() 和其他读取 stdio 的标准函数通常是面向行的,因此会阻塞直到换行。

An implementation of kbhit() for Linux is presented in Beginning Linux Programming page 167. You can read it on-line at the link provided.

EDIT: I mention kbhit() because it was posted as a solution before it was made clear that the question related to Linux. Unfortunately the solution has been deleted, which is unfortunate. The principle is that when kbhit() returns non-zero, a subsequent blocking character-oriented read call will not block. This is only true for character oriented input; getchar() and other standard functions that read stdio are typically line-oriented, so block until newline.

紫南 2024-08-13 18:44:30

多线程?

Multiple threads?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文