Mercurial > hg > toybox
comparison toys/which.c @ 20:3981c96f9285
Implement which. Add hello world to menuconfig. Wrap the various applet main
functions in main.c with USE() macros so --gc-sections can strip them.
author | Rob Landley <rob@landley.net> |
---|---|
date | Fri, 03 Nov 2006 00:05:52 -0500 |
parents | |
children | eb46bb5626cb |
comparison
equal
deleted
inserted
replaced
19:414625f97667 | 20:3981c96f9285 |
---|---|
1 /* vi: set sw=4 ts=4: */ | |
2 /* | |
3 * which.c - | |
4 * | |
5 * Copyright 2006 Rob landley <rob@landley.net> | |
6 */ | |
7 | |
8 #include "toys.h" | |
9 | |
10 #define OPTIONS "a" | |
11 #define OPT_a 1 | |
12 | |
13 // Find an exectuable file either at a path with a slash in it (absolute or | |
14 // relative to current directory), or in $PATH. Returns absolute path to file, | |
15 // or NULL if not found. | |
16 | |
17 static int which_in_path(char *filename) | |
18 { | |
19 struct string_list *list; | |
20 | |
21 // If they gave us a path, don't worry about $PATH or -a | |
22 | |
23 if (index(filename, '/')) { | |
24 // Confirm it has the executable bit set, and it's not a directory. | |
25 if (!access(filename, X_OK)) { | |
26 struct stat st; | |
27 | |
28 if (!stat(filename, &st) && S_ISREG(st.st_mode)) { | |
29 puts(filename); | |
30 return 0; | |
31 } | |
32 return 1; | |
33 } | |
34 } | |
35 | |
36 // Search $PATH for matches. | |
37 list = find_in_path(getenv("PATH"), filename); | |
38 if (!list) return 1; | |
39 | |
40 // Print out matches | |
41 while (list) { | |
42 if (!access(list->str, X_OK)) { | |
43 puts(list->str); | |
44 // If we should stop at one match, do so | |
45 if (toys.optflags & OPT_a) { | |
46 llist_free(list, NULL); | |
47 break; | |
48 } | |
49 } | |
50 free(llist_pop(&list)); | |
51 } | |
52 | |
53 return 0; | |
54 } | |
55 | |
56 int which_main(void) | |
57 { | |
58 char **argv; | |
59 int rc = 0; | |
60 | |
61 // get_optflags(OPTIONS); | |
62 argv = toys.argv+1; | |
63 | |
64 if (!*argv) rc++; | |
65 else { | |
66 int i; | |
67 for (i=0; argv[i]; i++) rc |= which_in_path(argv[i]); | |
68 } | |
69 // if (CFG_TOYS_FREE) free(argv); | |
70 | |
71 return rc; | |
72 } |