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

问题描述

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

When the user hits + 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.

(摘录自参考手册:)

瓦拉的一个例子:

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的正常终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:49
查看更多