]>
git.saurik.com Git - apple/shell_cmds.git/blob - which/which.c
2 * Copyright (c) 2000 Dan Papasian. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD: src/usr.bin/which/which.c,v 1.6 2005/02/10 16:04:22 ru Exp $");
32 #include <sys/param.h>
40 static void usage(void);
41 static int print_matches(char *, char *);
47 main(int argc
, char **argv
)
53 status
= EXIT_SUCCESS
;
55 while ((opt
= getopt(argc
, argv
, "as")) != -1) {
75 if ((p
= getenv("PATH")) == NULL
)
77 pathlen
= strlen(p
) + 1;
78 path
= malloc(pathlen
);
80 err(EXIT_FAILURE
, NULL
);
83 memcpy(path
, p
, pathlen
);
85 if (strlen(*argv
) >= FILENAME_MAX
||
86 print_matches(path
, *argv
) == -1)
87 status
= EXIT_FAILURE
;
100 (void)fprintf(stderr
, "usage: which [-as] program ...\n");
105 is_there(char *candidate
)
109 /* XXX work around access(2) false positives for superuser */
110 if (access(candidate
, X_OK
) == 0 &&
111 stat(candidate
, &fin
) == 0 &&
112 S_ISREG(fin
.st_mode
) &&
114 (fin
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)) != 0)) {
116 printf("%s\n", candidate
);
123 print_matches(char *path
, char *filename
)
125 char candidate
[PATH_MAX
];
129 if (strchr(filename
, '/') != NULL
)
130 return (is_there(filename
) ? 0 : -1);
132 while ((d
= strsep(&path
, ":")) != NULL
) {
135 if (snprintf(candidate
, sizeof(candidate
), "%s/%s", d
,
136 filename
) >= (int)sizeof(candidate
))
138 if (is_there(candidate
)) {
144 return (found
? 0 : -1);