wd

Workdir changer
git clone https://git.sinitax.com/sinitax/wd
Log | Files | Refs | LICENSE | sfeed.txt

commit 77291082d73fd8a59f57ed3430de22d8d87b3eb4
parent bf588e2dd965ba97befc374dba9eeaf89413ec24
Author: Louis Burda <quent.burda@gmail.com>
Date:   Thu,  9 Nov 2023 00:02:14 +0100

Use execvp() for path resolution

Diffstat:
Mwd.c | 83++++++++++---------------------------------------------------------------------
1 file changed, 10 insertions(+), 73 deletions(-)

diff --git a/wd.c b/wd.c @@ -1,87 +1,24 @@ -#include <linux/limits.h> #include <unistd.h> -#include <dirent.h> -#include <limits.h> -#include <stdio.h> #include <string.h> -#include <stdarg.h> -#include <stdlib.h> - -static void -__attribute__((noreturn)) -die(const char *fmt, ...) -{ - va_list ap; - - va_start(ap, fmt); - fprintf(stderr, "wd: "); - vfprintf(stderr, fmt, ap); - if (*fmt && fmt[strlen(fmt)-1] == ':') { - fputc(' ', stderr); - perror(NULL); - } else { - fputc('\n', stderr); - } - va_end(ap); - - exit(1); -} - -static char * -findbin(char *name) -{ - static char binpath[PATH_MAX]; - char *env, *tok; - struct dirent *ent; - int len; - DIR *d; - - if (!strncmp(name, "./", 2)) - return name; - - env = getenv("PATH"); - if (!env) die("PATH not set"); - - env = strdup(env); - if (!env) die("strdup:"); - - for (tok = strtok(env, ":"); tok; tok = strtok(NULL, ":")) { - if (!*tok) continue; - d = opendir(tok); - if (!d) continue; - while ((ent = readdir(d))) { - if (!strcmp(ent->d_name, name)) { - closedir(d); - free(env); - len = snprintf(binpath, PATH_MAX, - "%s/%s", tok, ent->d_name); - if (len > PATH_MAX) abort(); - return binpath; - } - } - closedir(d); - } - - free(env); - - die("'%s' not found", name); -} +#include <errno.h> +#include <stdio.h> int main(int argc, char **argv) { - char *binpath; - if (argc < 3) { fprintf(stderr, "Usage: wd DIR CMD..\n"); return 1; } - if (chdir(argv[1])) die("chdir %s:", argv[1]); - - binpath = findbin(argv[2]); + if (chdir(argv[1])) { + fprintf(stderr, "wd: chdir %s: %s\n", + argv[1], strerror(errno)); + return 1; + } - execv(binpath, argv + 2); + execvp(argv[2], argv + 2); - die("execv:"); + fprintf(stderr, "wd: execv: %s\n", strerror(errno)); + return 1; }