GLib:Unix SIGINT上的GApplication的正常终止 [英] GLib: Graceful termination of GApplication on Unix SIGINT

查看:229
本文介绍了GLib:Unix SIGINT上的GApplication的正常终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在运行程序的Posix/Linux外壳中按 Ctrl + C 时,该程序将收到SIGINT信号.当运行基于GApplication的程序时,这意味着该程序将立即终止.

When the user hits Ctrl+C in a Posix / Linux shell with a program running, that program recieves a SIGINT signal. When running a program based on GApplication, this means that the program gets terminated immediately.

如何克服这个问题并让GApplication正常关闭?

How can I overcome this and have GApplication shut down gracefully?

推荐答案

您可以使用g_unix_signal_add().一旦程序接收到您指定的信号,此函数将调用一个回调. (在这种情况下为SIGINT)

You can use g_unix_signal_add(). This function takes a callback that is called once the program recieves the signal you specify. (SIGINT in this case)

然后该回调应调用g_application_release(),直到GApplication的使用计数降至零为止.在这种情况下,主循环将终止,并发出GApplication的shutdown信号.通过处理该信号,您可以在程序终止之前执行所有必要的反初始化任务.

That callback should then call g_application_release() until the GApplication's use count dropped to zero. Once that is the case, the Main Loop will terminate and GApplication's shutdown signal will be emitted. By handling that signal you can do all necessary deinitialization tasks before the program will terminate.

(摘录自参考手册:)

GApplication通过维护主应用程序实例的使用计数"来提供便捷的生命周期管理.可以使用g_application_hold()和g_application_release()更改使用次数.如果下降到零,则应用程序退出.诸如GtkApplication之类的高级类使用使用计数来确保只要有打开的窗口,该应用程序就可以保持活动状态.

GApplication provides convenient life cycle management by maintaining a "use count" for the primary application instance. The use count can be changed using g_application_hold() and g_application_release(). If it drops to zero, the application exits. Higher-level classes such as GtkApplication employ the use count to ensure that the application stays alive as long as it has any opened windows.

瓦拉的一个例子:

public class MyApplication : Application {
    public MyApplication () {
        Object (flags: ApplicationFlags.FLAGS_NONE);

        startup.connect (on_startup);
        activate.connect (on_activate);
        shutdown.connect (on_shutdown);

        Unix.signal_add (
            Posix.SIGINT,
            on_sigint,
            Priority.DEFAULT
        );
    }

    private bool on_sigint () {
        release ();
        return Source.REMOVE;
    }

    private void on_startup () {
        print ("Startup\n");
    }

    private void on_activate () {
        print ("command line\n");
        hold ();
    }

    private void on_shutdown () {
        print ("Shutdown\n");
    }
}

void main (string[] args) {
    new MyApplication ().run ();
}

(使用valac foo.vala --pkg gio-2.0 --pkg posix编译)

这篇关于GLib:Unix SIGINT上的GApplication的正常终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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