如何在命令行界面中处理ctrl-break信号 [英] How to handle a ctrl-break signal in a command line interface

查看:249
本文介绍了如何在命令行界面中处理ctrl-break信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开始之前,我想澄清一下,这不是一个命令行工具,而是一个通过自己的命令行界面接受命令的应用程序。

Before I begin, I want to clarify that this is not a command-line tool, but an application that accepts commands through it's own command-line interface.

修改:我必须对之前的解释道歉,显然我没有做很好的解释。再一次...

I must apologize about my explanation from before, apparently I didn't do a very good job at explaining it. One more time...

我正在构建一个命令行界面应用程序,接受用户的命令。我有一个信号处理程序设置捕获的信号,然后设置一个标志,我需要终止应用程序。我遇到的问题是所有的控制台功能我可以发现是阻塞,这意味着我不能检测到我需要退出我的控制台处理循环,直到用户按下一个键(或输入,取决于功能)。

I am building a command-line interface application that accepts commands from a user. I have a signal handler setup to catch the signals, which then sets a flag that I need to terminate the application. The problem I'm having is all of the console functions I can find are blocking, which means that I can't detect that I need to exit from my console processing loop until the user presses a key (or enter, depending on the function).

有一些标准的方法,我可以做非块控制台交互,或者有一个优雅的方式来构造程序,如果我只是从信号线程,一切都将被正确处理和释放(请不要误解这个,我知道如何使用锁定和释放信号线程的资源,但这可能会弄乱,所以我宁愿避免它)

Is there some standard way I can do either non-block console interaction, or is there an elegant way to structure the program so that if I just terminate from the signal thread, that everything will be handled and released properly (please don't mis-understand this, I know how this could be done using locking and releasing the resources from the signaling thread, but this could get messy, so I'd rather avoid it)

希望这种解释更有意义...

Hopefully that explanation makes more sense...

推荐答案

p> OK - 这对我工作在Windows&可移植 - 注意#ifdef SIGBREAK - 这不是标准信号。

OK - this is working for me on Windows & is portable - notice the #ifdef SIGBREAK - this isn't a standard signal.

#include <csignal>
#include <iostream>
#include <ostream>
#include <string>
using namespace std;

namespace
{
    volatile sig_atomic_t quit;

    void signal_handler(int sig)
    {
        signal(sig, signal_handler);
        quit = 1;
    }
}

int main()
{
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
#ifdef SIGBREAK
    signal(SIGBREAK, signal_handler);
#endif
    /* etc */

    while (!quit)
    {
        string s;
        cin >> s;
        cout << s << endl;
    }
    cout << "quit = " << quit << endl;
}

这篇关于如何在命令行界面中处理ctrl-break信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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