diff --git a/README.md b/README.md index cad4071..48a7264 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,9 @@ Generic Functions `whichp()` is a predicate function, returns `TRUE` or `FALSE`. + **Note:** `which("/bin/ps aux")` will return `/bin/ps`, or `TRUE`, + provided of course `/bin/ps` exists. + GNU Functions ------------- diff --git a/which.c b/which.c index 0a53a77..4635900 100644 --- a/which.c +++ b/which.c @@ -14,12 +14,30 @@ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#include #include #include /* snprintf() */ #include /* realloc(), free() */ #include /* strtok_r() */ #include /* access() */ +/* Strip any arguments in "/path/to/bin --some args", modifies input string */ +static char *strip_args(char *path) +{ + size_t i = 0; + + if (!path) + return NULL; + + /* Find first whitespace (space/tab/etc.) */ + while (path[i] && !isspace(path[i])) + i++; + path[i] = 0; + + return path; +} + /* * Like which(1), returns a malloc'ed path to cmd on success, or NULL */ @@ -34,7 +52,10 @@ char *which(const char *cmd) } if (cmd[0] == '/') { - path = strdup(cmd); + path = strip_args(strdup(cmd)); + if (!path) + return NULL; + if (!access(path, X_OK)) return path; @@ -66,7 +87,8 @@ char *which(const char *cmd) } snprintf(path, pathlen, "%s/%s", tok, cmd); - if (!access(path, X_OK)) { + path = strip_args(path); + if (!path || !access(path, X_OK)) { free(env); return path; }