我试图编写一个模拟程序,直到我按下某个键(比如'q'表示退出)才停止运行。然后在我按下该键后,我希望程序继续写入当前正在写入的数据,关闭文件,然后优雅地退出(而不是强制按下ctrl+c来停止程序)。在C++中有没有办法实现这一点?
谢谢
谢谢
让用户按下CTRL-C,但安装一个信号处理程序来处理它。在信号处理程序中,设置一个全局布尔变量,例如user_wants_to_quit
。然后您的模拟循环可以如下所示:
while ( work_to_be_done && !user_wants_to_quit) {
…
}
// Loop exited, clean up my data
一个完整的POSIX程序(抱歉,如果你期望的是微软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";
}
}