Skip to content

Instantly share code, notes, and snippets.

@hewittc
Last active June 20, 2019 00:49
Show Gist options
  • Save hewittc/cd8cfaffddabe00763ddcf63fbbc6112 to your computer and use it in GitHub Desktop.
Save hewittc/cd8cfaffddabe00763ddcf63fbbc6112 to your computer and use it in GitHub Desktop.
gdbus systemd unit restart
//
// Restart a systemd unit through gdbus
//
// Compile:
// gcc $(pkg-config --libs --cflags gio-2.0 glib-2.0) -o bounce bounce.c
//
// Equivalent to:
// # gdbus call --system --dest org.freedesktop.systemd1 --object-path /org/freedesktop/systemd1/unit/whatever_2eservice --method org.freedesktop.systemd1.Unit.ReloadOrRestart replace
//
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <gio/gio.h>
static int bounce(GDBusConnection *connection, const gchar *owner, GError **error) {
GDBusMessage *method_call_message;
method_call_message = g_dbus_message_new_method_call(owner,
"/org/freedesktop/systemd1/unit/whatever_2eservice",
"org.freedesktop.systemd1.Unit",
"ReloadOrRestart");
g_dbus_message_set_body(method_call_message, g_variant_new("(s)", "replace"));
GDBusMessage *method_reply_message;
method_reply_message = g_dbus_connection_send_message_with_reply_sync (connection,
method_call_message,
G_DBUS_SEND_MESSAGE_FLAGS_NONE,
-1,
NULL,
NULL,
error);
int res = EXIT_SUCCESS;
if (!method_reply_message) {
res = EXIT_FAILURE;
} else if (g_dbus_message_get_message_type(method_reply_message) == G_DBUS_MESSAGE_TYPE_ERROR) {
g_dbus_message_to_gerror(method_reply_message, error);
res = EXIT_FAILURE;
}
g_object_unref(method_call_message);
g_object_unref(method_reply_message);
return res;
}
static void on_name_appeared (GDBusConnection *connection, const gchar *name, const gchar *owner, gpointer user_data) {
GError *error = NULL;
if (bounce(connection, owner, &error) == EXIT_SUCCESS) {
g_print("SUCCESS: Restarted the service\n");
exit(0);
} else {
g_print("FAILURE: Could not restart the service\n");
exit(1);
}
}
static void on_name_vanished (GDBusConnection *connection, const gchar *name, gpointer user_data) {
g_printerr("Failed to get owner for %s\n", name);
exit(1);
}
int main (int argc, char *argv[]) {
guint watcher_id;
watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM,
"org.freedesktop.systemd1",
G_BUS_NAME_WATCHER_FLAGS_NONE,
on_name_appeared,
on_name_vanished,
NULL,
NULL);
GMainLoop *loop;
loop = g_main_loop_new (NULL, FALSE);
g_main_loop_run(loop);
g_bus_unwatch_name(watcher_id);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment