[英]How to abort getchar in a console application when closing it
I've written a simple command line tool that uses getchar to wait for a termination signal (something like: 'Press enter to stop'). 我编写了一个简单的命令行工具,它使用getchar来等待终止信号(类似于:'按Enter键停止')。 I however also want to handle the SC_CLOSE case (clicking the 'close' button). 然而,我也想处理SC_CLOSE案例(单击“关闭”按钮)。 I did this by using SetConsoleCtrlHandler. 我是通过使用SetConsoleCtrlHandler完成的。 But how do I cancel my getchar? 但是如何取消我的getchar?
fputc('\\n', stdin);
我试过做fputc('\\n', stdin);
, but that results in a deadlock. ,但这会导致死锁。 Maybe there's some sort of getchar with a timeout that I can call instead? 也许有某种类型的getchar超时,我可以调用它?
You can read console input asynchronously: 您可以异步读取控制台输入:
#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;
}
In such a way, you can introduce bool bExit
flag which indicates if your programs is required to terminate. 通过这种方式,您可以引入bool bExit
标志,指示您的程序是否需要终止。 You can read input in specialized thread or wrap this code into the function and call it periodically. 您可以在专用线程中读取输入或将此代码包装到函数中并定期调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.