"Safely"按键终止正在运行的C++程序?

"Safely" terminate a running C++ program on keypress?

本文关键字:C++ 程序 运行 Safely 终止      更新时间:2023-10-16

我正在尝试编写一个模拟,该模拟将继续运行,直到我按下某个键(如"q"表示退出)。然后,在我按下后,我希望程序完成当前正在写入的数据的写入,关闭文件,然后优雅地退出(而不是只按ctrl+c来强制程序停止)。有什么方法可以在C++上做到这一点吗?

感谢

让用户按下CTRL-C,但安装一个信号处理程序来处理它。在信号处理程序中,设置一个全局布尔变量,例如user_wants_to_quit。然后你的sim循环可以看起来像:

while ( work_to_be_done && !user_wants_to_quit) {
 …
}
// Loop exited, clean up my data

一个完整的POSIX程序(抱歉,如果你希望使用Microsoft Windows),包括设置和恢复SIGINT(CTRL-C)处理程序:

#include <iostream>
#include <signal.h>
namespace {
  sig_atomic_t user_wants_to_quit = 0;
  void signal_handler(int) {
    user_wants_to_quit = 1;
  }
}
int main () {
  // Install signal handler
  struct sigaction act;
  struct sigaction oldact;
  act.sa_handler = signal_handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  sigaction(SIGINT, &act, &oldact);

  // Run the sim loop
  int sim_loop_counter = 3;
  while( (sim_loop_counter--) && !user_wants_to_quit) {
    std::cout << "Running sim step " << sim_loop_counter << std::endl;
    // Sim logic goes here. I'll substitute a sleep() for the actual
    // sim logic
    sleep(1);
    std::cout << "Step #" << sim_loop_counter << " is now complete." << std::endl;
  }
  // Restore old signal handler [optional]
  sigaction(SIGINT, &oldact, 0);
  if( user_wants_to_quit ) {
    std::cout << "SIM abortedn"; 
  } else {
    std::cout << "SIM completen";
  }
}