Zbigniew Jędrzejewski-Szmek | cfe8ee4 | 2018-07-26 20:00:36 +0200 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <string.h> |
| 3 | #include <unistd.h> |
| 4 | #include <sys/types.h> |
| 5 | |
| 6 | #include <systemd/sd-bus.h> |
| 7 | #define _cleanup_(f) __attribute__((cleanup(f))) |
| 8 | |
| 9 | /* This is equivalent to: |
| 10 | * busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 \ |
| 11 | * org.freedesktop.systemd1.Manager GetUnitByPID $$ |
| 12 | * |
| 13 | * Compile with 'cc -lsystemd print-unit-path.c' |
| 14 | */ |
| 15 | |
| 16 | #define DESTINATION "org.freedesktop.systemd1" |
| 17 | #define PATH "/org/freedesktop/systemd1" |
| 18 | #define INTERFACE "org.freedesktop.systemd1.Manager" |
| 19 | #define MEMBER "GetUnitByPID" |
| 20 | |
| 21 | static int log_error(int error, const char *message) { |
| 22 | fprintf(stderr, "%s: %s\n", message, strerror(-error)); |
| 23 | return error; |
| 24 | } |
| 25 | |
| 26 | static int print_unit_path(sd_bus *bus) { |
| 27 | _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; |
| 28 | _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; |
| 29 | _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; |
| 30 | int r; |
| 31 | |
| 32 | r = sd_bus_message_new_method_call(bus, &m, |
| 33 | DESTINATION, PATH, INTERFACE, MEMBER); |
| 34 | if (r < 0) |
| 35 | return log_error(r, "Failed to create bus message"); |
| 36 | |
| 37 | r = sd_bus_message_append(m, "u", (unsigned) getpid()); |
| 38 | if (r < 0) |
| 39 | return log_error(r, "Failed to append to bus message"); |
| 40 | |
| 41 | r = sd_bus_call(bus, m, -1, &error, &reply); |
| 42 | if (r < 0) |
| 43 | return log_error(r, "Call failed"); |
| 44 | |
| 45 | const char *ans; |
| 46 | r = sd_bus_message_read(reply, "o", &ans); |
| 47 | if (r < 0) |
| 48 | return log_error(r, "Failed to read reply"); |
| 49 | |
| 50 | printf("Unit path is \"%s\".\n", ans); |
| 51 | |
| 52 | return 0; |
| 53 | } |
| 54 | |
| 55 | int main(int argc, char **argv) { |
| 56 | _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; |
| 57 | int r; |
| 58 | |
| 59 | r = sd_bus_open_system(&bus); |
| 60 | if (r < 0) |
| 61 | return log_error(r, "Failed to acquire bus"); |
| 62 | |
| 63 | print_unit_path(bus); |
| 64 | } |