[英]How to abort getchar in a console application when closing it
我編寫了一個簡單的命令行工具,它使用getchar來等待終止信號(類似於:'按Enter鍵停止')。 然而,我也想處理SC_CLOSE案例(單擊“關閉”按鈕)。 我是通過使用SetConsoleCtrlHandler完成的。 但是如何取消我的getchar?
fputc('\\n', stdin);
,但這會導致死鎖。 也許有某種類型的getchar超時,我可以調用它?
您可以異步讀取控制台輸入:
#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
標志,指示您的程序是否需要終止。 您可以在專用線程中讀取輸入或將此代碼包裝到函數中並定期調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.