简体   繁体   English

如何在关闭它时在控制台应用程序中中止getchar

[英]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?

  • I tried doing fputc('\\n', stdin); 我试过做fputc('\\n', stdin); , but that results in a deadlock. ,但这会导致死锁。
  • I can call ExitProcess, but then I get a crash in CThreadLocalObject::GetData when deleting a global CWnd, because the CThreadLocalObject is already deleted (okay, maybe I was lying when claiming it was a simple console application). 我可以调用ExitProcess,但是当删除全局CWnd时,我在CThreadLocalObject :: GetData中出现崩溃,因为CThreadLocalObject已经被删除了(好吧,也许我说谎时声称它是一个简单的控制台应用程序)。 I guess this might have something to do with the fact that the HandlerRoutine is called from a separate thread (not the main thread). 我想这可能与HandlerRoutine是从一个单独的线程(而不是主线程)调用的事实有关。
  • Maybe there's some sort of getchar with a timeout that I can call instead? 也许有某种类型的getchar超时,我可以调用它?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM