]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/systemctl/systemctl-is-active.c
18eba2d82e40a944fe4757d46bf711c90f678b07
[thirdparty/systemd.git] / src / systemctl / systemctl-is-active.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include "bus-error.h"
4 #include "bus-locator.h"
5 #include "pretty-print.h"
6 #include "syslog-util.h"
7 #include "systemctl-is-active.h"
8 #include "systemctl-sysv-compat.h"
9 #include "systemctl-util.h"
10 #include "systemctl.h"
11
12 static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
13 _cleanup_strv_free_ char **names = NULL;
14 UnitActiveState active_state;
15 sd_bus *bus;
16 char **name;
17 int r, i;
18 bool found = false;
19
20 r = acquire_bus(BUS_MANAGER, &bus);
21 if (r < 0)
22 return r;
23
24 r = expand_unit_names(bus, args, NULL, &names, NULL);
25 if (r < 0)
26 return log_error_errno(r, "Failed to expand names: %m");
27
28 STRV_FOREACH(name, names) {
29 r = get_state_one_unit(bus, *name, &active_state);
30 if (r < 0)
31 return r;
32
33 if (!arg_quiet)
34 puts(unit_active_state_to_string(active_state));
35
36 for (i = 0; i < nb_states; ++i)
37 if (good_states[i] == active_state)
38 found = true;
39 }
40
41 /* use the given return code for the case that we won't find
42 * any unit which matches the list */
43 return found ? 0 : code;
44 }
45
46 int check_unit_active(int argc, char *argv[], void *userdata) {
47 static const UnitActiveState states[] = {
48 UNIT_ACTIVE,
49 UNIT_RELOADING,
50 };
51
52 /* According to LSB: 3, "program is not running" */
53 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
54 }
55
56 int check_unit_failed(int argc, char *argv[], void *userdata) {
57 static const UnitActiveState states[] = {
58 UNIT_FAILED,
59 };
60
61 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
62 }