diff options
author | Joseph Hunkeler <jhunkeler@gmail.com> | 2023-02-09 20:28:29 -0500 |
---|---|---|
committer | Joseph Hunkeler <jhunkeler@gmail.com> | 2023-02-09 20:28:29 -0500 |
commit | 32e01ad647ff347b0395e2a98863dcc426cd8f72 (patch) | |
tree | 67dabfb75417fb489aeb09a9c7567dfe358205d8 | |
parent | 97c79ae01a7bd761789259842e7d38e2cc723048 (diff) | |
download | mstat-32e01ad647ff347b0395e2a98863dcc426cd8f72.tar.gz |
Move find_program to common
* Add ability to return the path to program
-rw-r--r-- | common.c | 44 | ||||
-rw-r--r-- | common.h | 1 |
2 files changed, 44 insertions, 1 deletions
@@ -569,4 +569,46 @@ void mstat_get_mmax(const double a[], size_t size, double *min, double *max) { *min = a[i]; } } -}
\ No newline at end of file +} + +/** + * Determine if `name` is available on `PATH` + * @param name of executable + * @return 0 on success. >0 on error + */ +int mstat_find_program(const char *name, char *where) { + char *path; + char *pathtmp; + char *path_orig; + char *token; + char pathtest[PATH_MAX] = {0}; + char nametmp[PATH_MAX] = {0}; + + pathtmp = getenv("PATH"); + if (!pathtmp) { + return 1; + } + path = strdup(pathtmp); + path_orig = path; + + char *last_element = strrchr(name, '/'); + if (last_element) { + strncpy(nametmp, last_element + 1, sizeof(nametmp) - 1); + } else { + strncpy(nametmp, name, sizeof(nametmp) - 1); + } + + while ((token = strsep(&path, ":")) != NULL) { + snprintf(pathtest, PATH_MAX - 1, "%s/%s", token, nametmp); + if (access(pathtest, F_OK | X_OK) == 0) { + if (where) { + strcpy(where, pathtest); + } + free(path_orig); + return 0; + } + } + free(path); + return 1; +} + @@ -85,5 +85,6 @@ int mstat_write(FILE *fp, struct mstat_record_t *p); int mstat_iter(FILE *fp, struct mstat_record_t *p); void mstat_get_mmax(const double a[], size_t size, double *min, double *max); double mstat_difftimespec(struct timespec end, struct timespec start); +int mstat_find_program(const char *name, char *where); #endif //MSTAT_COMMON_H |