| 1 |
#include <gio/gio.h> |
| 2 |
|
| 3 |
static gchar *opt_name = NULL; |
| 4 |
static gboolean opt_system_bus = FALSE; |
| 5 |
static gboolean opt_auto_start = FALSE; |
| 6 |
|
| 7 |
static GOptionEntry opt_entries[] = |
| 8 |
{ |
| 9 |
{ "name", 'n', 0, G_OPTION_ARG_STRING, &opt_name, "Name to watch", NULL }, |
| 10 |
{ "system-bus", 's', 0, G_OPTION_ARG_NONE, &opt_system_bus, "Use the system-bus instead of the session-bus", NULL }, |
| 11 |
{ "auto-start", 'a', 0, G_OPTION_ARG_NONE, &opt_auto_start, "Instruct the bus to launch an owner for the name", NULL}, |
| 12 |
G_OPTION_ENTRY_NULL |
| 13 |
}; |
| 14 |
|
| 15 |
static void |
| 16 |
on_name_appeared (GDBusConnection *connection, |
| 17 |
const gchar *name, |
| 18 |
const gchar *name_owner, |
| 19 |
gpointer user_data) |
| 20 |
{ |
| 21 |
g_print ("Name %s on %s is owned by %s\n", |
| 22 |
name, |
| 23 |
opt_system_bus ? "the system bus" : "the session bus", |
| 24 |
name_owner); |
| 25 |
} |
| 26 |
|
| 27 |
static void |
| 28 |
on_name_vanished (GDBusConnection *connection, |
| 29 |
const gchar *name, |
| 30 |
gpointer user_data) |
| 31 |
{ |
| 32 |
g_print ("Name %s does not exist on %s\n", |
| 33 |
name, |
| 34 |
opt_system_bus ? "the system bus" : "the session bus"); |
| 35 |
} |
| 36 |
|
| 37 |
int |
| 38 |
main (int argc, char *argv[]) |
| 39 |
{ |
| 40 |
guint watcher_id; |
| 41 |
GMainLoop *loop; |
| 42 |
GOptionContext *opt_context; |
| 43 |
GError *error; |
| 44 |
GBusNameWatcherFlags flags; |
| 45 |
|
| 46 |
error = NULL; |
| 47 |
opt_context = g_option_context_new ("g_bus_watch_name() example"); |
| 48 |
g_option_context_set_summary (opt_context, |
| 49 |
"Example: to watch the power manager on the session bus, use:\n" |
| 50 |
"\n" |
| 51 |
" ./example-watch-name -n org.gnome.PowerManager"); |
| 52 |
g_option_context_add_main_entries (opt_context, opt_entries, NULL); |
| 53 |
if (!g_option_context_parse (opt_context, &argc, &argv, &error)) |
| 54 |
{ |
| 55 |
g_printerr ("Error parsing options: %s", error->message); |
| 56 |
goto out; |
| 57 |
} |
| 58 |
if (opt_name == NULL) |
| 59 |
{ |
| 60 |
g_printerr ("Incorrect usage, try --help.\n"); |
| 61 |
goto out; |
| 62 |
} |
| 63 |
|
| 64 |
flags = G_BUS_NAME_WATCHER_FLAGS_NONE; |
| 65 |
if (opt_auto_start) |
| 66 |
flags |= G_BUS_NAME_WATCHER_FLAGS_AUTO_START; |
| 67 |
|
| 68 |
watcher_id = g_bus_watch_name (opt_system_bus ? G_BUS_TYPE_SYSTEM : G_BUS_TYPE_SESSION, |
| 69 |
opt_name, |
| 70 |
flags, |
| 71 |
on_name_appeared, |
| 72 |
on_name_vanished, |
| 73 |
NULL, |
| 74 |
NULL); |
| 75 |
|
| 76 |
loop = g_main_loop_new (NULL, FALSE); |
| 77 |
g_main_loop_run (loop); |
| 78 |
|
| 79 |
g_bus_unwatch_name (watcher_id); |
| 80 |
|
| 81 |
out: |
| 82 |
g_option_context_free (opt_context); |
| 83 |
g_free (opt_name); |
| 84 |
|
| 85 |
return 0; |
| 86 |
} |