我编写了一个简单的命令行工具,它使用 getchar 来等待终止信号(类似于:“按回车键停止”)。然而,我也想处理 SC_CLOSE 案例(单击“关闭”按钮)。我通过使用 SetConsoleCtrlHandler 来完成此操作。但是如何取消我的 getchar?
- 我尝试执行
fputc('\n', stdin);
,但这会导致死锁。 - 我可以调用 ExitProcess,但是在删除全局 CWnd 时我在 CThreadLocalObject::GetData 中发生崩溃,因为 CThreadLocalObject 已经被删除(好吧,我声称它是一个简单的控制台应用程序时可能是在撒谎)。我想这可能与 HandlerRoutine 是从一个单独的线程(而不是主线程)调用这一事实有关。
- 也许我可以调用某种带有超时的 getchar?
最佳答案
Maybe there's some sort of getchar with a timeout that I can call instead?
您可以异步读取控制台输入:
#ifdef WIN32
#include <conio.h>
#else
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#endif
int main(int argc, char* argv[])
{
while(1)
{
#ifdef WIN32
if (kbhit()){
return getc(stdin);
}else{
Sleep(1000);
printf("I am still waiting for your input...\n");
}
#else
struct timeval tWaitTime;
tWaitTime.tv_sec = 1; //seconds
tWaitTime.tv_usec = 0; //microseconds
fd_set fdInput;
FD_ZERO(&fdInput);
FD_SET(STDIN_FILENO, &fdInput);
int n = (int) STDIN_FILENO + 1;
if (!select(n, &fdInput, NULL, NULL, &tWaitTime))
{
printf("I am still waiting for your input...\n");
}else
{
return getc(stdin);
}
#endif
}
return 0;
}
通过这种方式,您可以引入 bool bExit
标志,指示您的程序是否需要终止。您可以在专门的线程中读取输入或将此代码包装到函数中并定期调用它。
关于c++ - 关闭时如何在控制台应用程序中中止 getchar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642696/