GLib:在 Unix SIGINT 上优雅地终止 GApplication
GLib: Graceful termination of GApplication on Unix SIGINT
当用户在 Posix / Linux shell 中按下 Ctrl+C 时使用程序 运行,该程序接收到 SIGINT 信号。当运行一个基于GApplication的程序时,这意味着该程序会立即终止。
我怎样才能克服这个问题并让 GApplication 正常关闭?
您可以使用 g_unix_signal_add()
。一旦程序收到您指定的信号,此函数就会调用一个回调。 (在本例中为 SIGINT)
该回调应调用 g_application_release()
,直到 GApplication 的使用计数降为零。一旦出现这种情况,主循环将终止并发出 GApplication 的 shutdown
信号。通过处理该信号,您可以在程序终止之前执行所有必要的取消初始化任务。
(取自reference manual:)
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.
Vala 中的示例:
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
编译)
当用户在 Posix / Linux shell 中按下 Ctrl+C 时使用程序 运行,该程序接收到 SIGINT 信号。当运行一个基于GApplication的程序时,这意味着该程序会立即终止。
我怎样才能克服这个问题并让 GApplication 正常关闭?
您可以使用 g_unix_signal_add()
。一旦程序收到您指定的信号,此函数就会调用一个回调。 (在本例中为 SIGINT)
该回调应调用 g_application_release()
,直到 GApplication 的使用计数降为零。一旦出现这种情况,主循环将终止并发出 GApplication 的 shutdown
信号。通过处理该信号,您可以在程序终止之前执行所有必要的取消初始化任务。
(取自reference manual:)
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.
Vala 中的示例:
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
编译)