]> git.ipfire.org Git - thirdparty/systemd.git/blob - man/print-unit-path.c
Merge pull request #31648 from neighbourhoodie/review-content
[thirdparty/systemd.git] / man / print-unit-path.c
1 /* SPDX-License-Identifier: MIT-0 */
2
3 /* This is equivalent to:
4 * busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 \
5 * org.freedesktop.systemd1.Manager GetUnitByPID $$
6 *
7 * Compile with 'cc print-unit-path.c -lsystemd'
8 */
9
10 #include <errno.h>
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14
15 #include <systemd/sd-bus.h>
16
17 #define _cleanup_(f) __attribute__((cleanup(f)))
18 #define DESTINATION "org.freedesktop.systemd1"
19 #define PATH "/org/freedesktop/systemd1"
20 #define INTERFACE "org.freedesktop.systemd1.Manager"
21 #define MEMBER "GetUnitByPID"
22
23 static int log_error(int error, const char *message) {
24 fprintf(stderr, "%s: %s\n", message, strerror(-error));
25 return error;
26 }
27
28 int main(int argc, char **argv) {
29 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = 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, *m = NULL;
32 int r;
33
34 r = sd_bus_open_system(&bus);
35 if (r < 0)
36 return log_error(r, "Failed to acquire bus");
37
38 r = sd_bus_message_new_method_call(bus, &m,
39 DESTINATION, PATH, INTERFACE, MEMBER);
40 if (r < 0)
41 return log_error(r, "Failed to create bus message");
42
43 r = sd_bus_message_append(m, "u", (unsigned) getpid());
44 if (r < 0)
45 return log_error(r, "Failed to append to bus message");
46
47 r = sd_bus_call(bus, m, -1, &error, &reply);
48 if (r < 0)
49 return log_error(r, MEMBER " call failed");
50
51 const char *ans;
52 r = sd_bus_message_read(reply, "o", &ans);
53 if (r < 0)
54 return log_error(r, "Failed to read reply");
55
56 printf("Unit path is \"%s\".\n", ans);
57
58 return 0;
59 }