我正在尝试编写一个继续运行的模拟,直到我按下某个键(如'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
Run Code Online (Sandbox Code Playgroud)
一个完整的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";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4490 次 |
| 最近记录: |