Windows Ctrl-C - 在命令行应用程序中清除本地堆栈对象 [英] Windows Ctrl-C - Cleaning up local stack objects in command line app

查看:293
本文介绍了Windows Ctrl-C - 在命令行应用程序中清除本地堆栈对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个控制台应用程序Windows在主线程中创建一些对象,并将它们踢到循环中,只有当用户使用Ctrl-C中断时退出。



现在,我已经阅读了一些关于如何在这样的文章中编写一个正确的中断处理程序: http://msdn.microsoft.com/en-us/library/ms685049%28VS.85%29.aspx a>但我仍然困惑一件事。看起来中断处理程序留下局部对象清理的有限范围。例如,如果我有一个这样的处理程序:

  BOOL CtrlHandler(DWORD fdwCtrlType)
...句柄Ctrl -C

,我的主人看起来像这样:


$ b b

  int main(){
DBClient db;
DataPuller p;

while(true){
...直到Ctrl-C输入
才执行操作}

即使捕获了Ctrl-C,似乎也没有办法对变量db和p进行适当的清理,而没有声明它们是全局的,我通常远离。 / p>

有没有更好的方法来做到这一点,或者我缺少一些明显的东西?感谢。

解决方案

您可以对条件变量进行循环。



当您接收ctrl-C(SIGINT)时,您将条件变量设置为false并返回。
然后循环将正常退出。

  bool finished = false; 

int main()
{
DBClient db;
DataPuller p;

while(!finished)
{
// ...直到Ctrl-C输入
才执行操作}
}

//窗口上的信号处理程序或控制处理程序
//设置finished = true。


I'm writing a console application Windows that creates some objects in the main thread and kicks those off into a loop, only exiting when the user uses the Ctrl-C interrupt.

Now, I've read a bit about how to write a proper interrupt handler in articles like this: http://msdn.microsoft.com/en-us/library/ms685049%28VS.85%29.aspx but I'm still confused about one thing. It seems like the interrupt handler leaves limited scope for local object cleanup. For instance, if I had a handler like so:

BOOL CtrlHandler ( DWORD fdwCtrlType )
  ... handle Ctrl-C 

and my main looked something like this:

int main() {
      DBClient db;
      DataPuller p;

      while (true) {
           ... do stuff until Ctrl-C comes in
      }

Even if I catch the Ctrl-C, there seems to be no way to do a proper cleanup of variables db and p without declaring them global, which I typically stay away from.

Is there a better way to do this, or am I missing something obvious? Thanks.

解决方案

You make your loop on a condition variable.

When you receive ctrl-C (SIGINT) you set the condition variable to false and return. The loop will then exit normally.

bool finished = false;

int main()
{
      DBClient db;
      DataPuller p;

      while (!finished)
      {
           // ... do stuff until Ctrl-C comes in
      }
}

// Signal handler or Control handler on windows
// Set finished = true.

这篇关于Windows Ctrl-C - 在命令行应用程序中清除本地堆栈对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆