“安全地”终止在按键上运行的C ++程序?

时间:2012-03-19 19:37:44

标签: c++ keyboard exit

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

由于

1 个答案:

答案 0 :(得分:5)

让用户按 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 aborted\n"; 
  } else {
    std::cout << "SIM complete\n";
  }

}