1
0
mirror of git://git.suckless.org/sbase synced 2024-12-22 23:13:44 +00:00
sbase/which.c

90 lines
1.4 KiB
C
Raw Normal View History

2015-04-27 18:33:23 +00:00
/* See LICENSE file for copyright and license details. */
2015-04-27 14:24:43 +00:00
#include <sys/stat.h>
#include <sys/types.h>
2015-04-27 14:24:43 +00:00
#include <fcntl.h>
2015-04-27 14:24:43 +00:00
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
static int aflag;
static int
which(const char *path, const char *name)
{
char *ptr, *p;
size_t i, len;
2015-04-27 14:24:43 +00:00
struct stat st;
int dirfd, found = 0;
2015-04-27 14:24:43 +00:00
ptr = p = enstrdup(3, path);
len = strlen(p);
for (i = 0; i < len + 1; i++) {
if (ptr[i] != ':' && ptr[i] != '\0')
continue;
ptr[i] = '\0';
if ((dirfd = open(p, O_RDONLY, 0)) >= 0) {
if (!fstatat(dirfd, name, &st, 0) &&
S_ISREG(st.st_mode) &&
!faccessat(dirfd, name, X_OK, 0)) {
found = 1;
fputs(p, stdout);
if (i && ptr[i - 1] != '/')
fputc('/', stdout);
puts(name);
if (!aflag) {
close(dirfd);
break;
}
}
close(dirfd);
2015-04-27 14:24:43 +00:00
}
p = ptr + i + 1;
2015-04-27 14:24:43 +00:00
}
free(ptr);
return found;
}
static void
usage(void)
{
eprintf("usage: %s [-a] name ...\n", argv0);
2015-04-27 14:24:43 +00:00
}
int
main(int argc, char *argv[])
{
char *path;
int found = 0, foundall = 1;
2015-04-27 14:24:43 +00:00
ARGBEGIN {
case 'a':
aflag = 1;
break;
default:
usage();
} ARGEND
2015-04-27 14:24:43 +00:00
if (!argc)
usage();
if (!(path = getenv("PATH")))
enprintf(3, "$PATH is not set\n");
2015-04-27 14:24:43 +00:00
for (; *argv; argc--, argv++) {
if (which(path, *argv)) {
found = 1;
} else {
weprintf("%s: command not found.\n", *argv);
foundall = 0;
}
2015-04-27 14:24:43 +00:00
}
return found ? foundall ? 0 : 1 : 2;
2015-04-27 14:24:43 +00:00
}