keyboardinterrupt - 键盘中断例程 Visual Studio C++ 控制台应用程序
问题描述
我正在使用 VS 2022 Preview 编写 C++ 控制台应用程序。我希望检测键盘敲击并调用我的中断处理函数。我希望快速检测到按键,以防 main 处于长循环中,因此不使用 kbhit()。
我找到了 signal() 但是当检测到 Control-C 时调试器停止。也许这是 IDE 的特性。是否有我应该使用的函数或系统调用?
编辑:我隐约知道线程。我可以生成一个只监视 kbd 的线程,然后在按下键时让它引发(?)中断吗?
解决方案
我能够通过添加一个线程来做到这一点。在目标上,我将有真正的中断来触发我的 ISR,但这对于算法开发来说已经足够接近了。似乎终止线程比它的价值更麻烦,所以我合理化了我正在模拟一个不需要花哨关闭的嵌入式系统。
我决定在虚假的 ISR 中一次只接受一个字符,然后当我看到一个简单的命令行处理器 CR 时,我可以缓冲它们并等待并处理整个字符串。
// Scheduler.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <iostream>
#include <thread>
#include <conio.h>
void phonyISR(int tbd)
{
char c;
while (1)
{
std::cout << "\nphonyISR() waiting for kbd input:";
c = _getch();
std::cout << "\nGot >" << c << "<";
}
}
int main(int argc, char* argv[])
{
int tbd;
std::thread t = std::thread(phonyISR, tbd);
// Main thread doing its stuff
int i = 0;
while (1)
{
Sleep(2000);
std::cout << "\nMain: " << i++;
}
return 0;
}
推荐阅读
- c - 在带有 Syntastic 的 Vim 上的 C 文件中使用 NULL 的问题
- sprite-kit - 如何在 Spritekit 中显示警报框?
- python - 美丽的汤找不到所有
标签
- flutter - Flutter async await http.post,与后端的状态不匹配
- javascript - Switch 语句不切换
- mysql - Unidac / MyDac / SQL - 我在快速插入大约 1000 行时遇到问题
- angular - EventEmitter 发出数据但不发出事件
- ios - 让 SwiftUI 一次显示一个列表项
- spring - 尝试在 Spring AOP 中使用目标切入点指示符时出错
- c - C语言中的红黑树删除