簡體   English   中英

如何在關閉它時在控制台應用程序中中止getchar

[英]How to abort getchar in a console application when closing it

我編寫了一個簡單的命令行工具,它使用getchar來等待終止信號(類似於:'按Enter鍵停止')。 然而,我也想處理SC_CLOSE案例(單擊“關閉”按鈕)。 我是通過使用SetConsoleCtrlHandler完成的。 但是如何取消我的getchar?

  • 我試過做fputc('\\n', stdin); ,但這會導致死鎖。
  • 我可以調用ExitProcess,但是當刪除全局CWnd時,我在CThreadLocalObject :: GetData中出現崩潰,因為CThreadLocalObject已經被刪除了(好吧,也許我說謊時聲稱它是一個簡單的控制台應用程序)。 我想這可能與HandlerRoutine是從一個單獨的線程(而不是主線程)調用的事實有關。
  • 也許有某種類型的getchar超時,我可以調用它?

也許有某種類型的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM