Debian Codegraph @

src/login/test-inhibit.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <unistd.h>
5
6 #include "sd-bus.h"
7
8 #include "bus-locator.h"
9 #include "fd-util.h"
10 #include "tests.h"
11
12 static int inhibit(sd_bus *bus, const char *what) {
13 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
14 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
15 const char *who = "Test Tool", *reason = "Just because!", *mode = "block";
16 int fd;
17 int r;
18
19 r = bus_call_method(bus, bus_login_mgr, "Inhibit", &error, &reply, "ssss", what, who, reason, mode);
20 assert_se(r >= 0);
21
22 r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_UNIX_FD, &fd);
23 assert_se(r >= 0);
24 assert_se(fd >= 0);
25
26 return fcntl(fd, F_DUPFD_CLOEXEC, 3);
27 }
28
29 static void print_inhibitors(sd_bus *bus) {
30 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
31 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
32 const char *what, *who, *why, *mode;
33 uint32_t uid, pid;
34 unsigned n = 0;
35 int r;
36
37 r = bus_call_method(bus, bus_login_mgr, "ListInhibitors", &error, &reply, NULL);
38 assert_se(r >= 0);
39
40 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
41 assert_se(r >= 0);
42
43 while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
44 printf("what=<%s> who=<%s> why=<%s> mode=<%s> uid=<%"PRIu32"> pid=<%"PRIu32">\n",
45 what, who, why, mode, uid, pid);
46
47 n++;
48 }
49 assert_se(r >= 0);
50
51 printf("%u inhibitors\n", n);
52 }
53
54 int main(int argc, char *argv[]) {
55 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
56 int fd1, fd2;
57 int r;
58
59 test_setup_logging(LOG_DEBUG);
60
61 r = sd_bus_open_system(&bus);
62 assert_se(r >= 0);
63
64 print_inhibitors(bus);
65
66 fd1 = inhibit(bus, "sleep");
67 assert_se(fd1 >= 0);
68 print_inhibitors(bus);
69
70 fd2 = inhibit(bus, "idle:shutdown");
71 assert_se(fd2 >= 0);
72 print_inhibitors(bus);
73
74 safe_close(fd1);
75 sleep(1);
76 print_inhibitors(bus);
77
78 safe_close(fd2);
79 sleep(1);
80 print_inhibitors(bus);
81
82 return 0;
83 }