We often have a pattern where the same verb function is used for multiple actions. This leads to an antipattern where we figure out what action needs to be taken from argv[0] multiple times: often once in parse_argv() to figure out what options are allowed, then once again implicitly in dispatch_verb(), and then again in the action verb itself. Let's allow passing a parameter into the verb to simplify this. This matches a pattern we have in conf-parser.h, where we have both void *userdata (more global) and void *data (per-config item). Here, I opted for uintptr_t userdata. It seems that most of the time we'll want to just pass an enum value. This works OK with no casts. I also tried a void* and union. In both cases, much more boilerplate is needed: either a cast or a macro to help avoid compiler warnings. uintptr_t seems generic enough to cover foreseeable usecases with no fuss. This is a noop refactoring. See next commit for an example.
56 lines
1.6 KiB
C
56 lines
1.6 KiB
C
/* SPDX-License-Identifier: LGPL-2.1-or-later */
|
|
|
|
#include <stdio.h>
|
|
|
|
#include "alloc-util.h"
|
|
#include "bus-util.h"
|
|
#include "errno-util.h"
|
|
#include "parse-util.h"
|
|
#include "strv.h"
|
|
#include "systemctl.h"
|
|
#include "systemctl-util.h"
|
|
#include "systemctl-whoami.h"
|
|
|
|
int verb_whoami(int argc, char *argv[], uintptr_t _data, void *userdata) {
|
|
sd_bus *bus;
|
|
int r, ret = 0;
|
|
|
|
r = acquire_bus(BUS_FULL, &bus);
|
|
if (r < 0)
|
|
return r;
|
|
|
|
if (argc <= 1) {
|
|
_cleanup_free_ char *unit = NULL;
|
|
|
|
if (arg_transport != BUS_TRANSPORT_LOCAL)
|
|
return log_error_errno(SYNTHETIC_ERRNO(EREMOTE),
|
|
"Refusing to look up our local PID on remote host.");
|
|
|
|
/* Our own process can never go away while querying, hence no need to go through pidfd. */
|
|
|
|
r = get_unit_by_pid(bus, 0, &unit, /* ret_path= */ NULL);
|
|
if (r < 0)
|
|
return r;
|
|
|
|
puts(unit);
|
|
return 0;
|
|
}
|
|
|
|
STRV_FOREACH(pidstr, strv_skip(argv, 1)) {
|
|
_cleanup_free_ char *unit = NULL;
|
|
pid_t pid;
|
|
|
|
r = parse_pid(*pidstr, &pid);
|
|
if (r < 0)
|
|
return log_error_errno(r, "Invalid PID specified: %s", *pidstr);
|
|
|
|
r = lookup_unit_by_pidref(bus, pid, &unit, /* ret_path= */ NULL);
|
|
if (r < 0)
|
|
RET_GATHER(ret, r);
|
|
else
|
|
puts(unit);
|
|
}
|
|
|
|
return ret;
|
|
}
|