aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoseph Hunkeler <jhunkeler@gmail.com>2023-02-09 20:28:29 -0500
committerJoseph Hunkeler <jhunkeler@gmail.com>2023-02-09 20:28:29 -0500
commit32e01ad647ff347b0395e2a98863dcc426cd8f72 (patch)
tree67dabfb75417fb489aeb09a9c7567dfe358205d8
parent97c79ae01a7bd761789259842e7d38e2cc723048 (diff)
downloadmstat-32e01ad647ff347b0395e2a98863dcc426cd8f72.tar.gz
Move find_program to common
* Add ability to return the path to program
-rw-r--r--common.c44
-rw-r--r--common.h1
2 files changed, 44 insertions, 1 deletions
diff --git a/common.c b/common.c
index 9602867..f9a8944 100644
--- a/common.c
+++ b/common.c
@@ -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;
+}
+
diff --git a/common.h b/common.h
index ccdf7e8..703c3a4 100644
--- a/common.h
+++ b/common.h
@@ -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