6 #include <systemd/sd-bus.h>
7 #define _cleanup_(f) __attribute__((cleanup(f)))
9 /* This is equivalent to:
10 * busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 \
11 * org.freedesktop.systemd1.Manager GetUnitByPID $$
13 * Compile with 'cc -lsystemd print-unit-path.c'
16 #define DESTINATION "org.freedesktop.systemd1"
17 #define PATH "/org/freedesktop/systemd1"
18 #define INTERFACE "org.freedesktop.systemd1.Manager"
19 #define MEMBER "GetUnitByPID"
21 static int log_error(int error
, const char *message
) {
22 fprintf(stderr
, "%s: %s\n", message
, strerror(-error
));
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
;
32 r
= sd_bus_message_new_method_call(bus
, &m
,
33 DESTINATION
, PATH
, INTERFACE
, MEMBER
);
35 return log_error(r
, "Failed to create bus message");
37 r
= sd_bus_message_append(m
, "u", (unsigned) getpid());
39 return log_error(r
, "Failed to append to bus message");
41 r
= sd_bus_call(bus
, m
, -1, &error
, &reply
);
43 return log_error(r
, "Call failed");
46 r
= sd_bus_message_read(reply
, "o", &ans
);
48 return log_error(r
, "Failed to read reply");
50 printf("Unit path is \"%s\".\n", ans
);
55 int main(int argc
, char **argv
) {
56 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
59 r
= sd_bus_open_system(&bus
);
61 return log_error(r
, "Failed to acquire bus");