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