#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
+#include <string.h>
#include <sys/stat.h>
#include <sys/inotify.h>
const int true = 1;
const int false = 0;
+char *file_path = NULL; // from argv
+char *comm = NULL; // to be freed
+
const char* init_watch(int *fd, int *wd, char *path) {
*fd = inotify_init();
return true;
}
+size_t strsize(char *str) {
+ return (strlen(str) + 1) * sizeof(char);
+}
+
+char* load_config(int argc, char **argv) {
+ int i, what, comm_flag = -1, tot_len;
+
+ for (i = 1; i < argc && comm_flag == -1; ++i) {
+ char *arg = argv[i];
+
+ if (strncmp(arg, "--path", strsize("--path")) == 0 || strncmp(arg, "-p", strsize("-p")) == 0) {
+ if (i == argc - 1) {
+ return "could not read path: no more args";
+ }
+
+ file_path = argv[++i];
+
+ continue;
+ }
+
+ if (strncmp(arg, "--comm", strsize("--comm")) == 0 || strncmp(arg, "-c", strsize("-c")) == 0) {
+ if (i == argc - 1) {
+ return "could not read coomand: no more args";
+ }
+
+ comm_flag = i;
+ continue;
+ }
+ }
+
+ if (comm_flag == -1) {
+ return "no command provided";
+ }
+
+ for (i = comm_flag + 1; i < argc; ++i) {
+ tot_len += strlen(argv[i]) + 1;
+ }
+ tot_len += 1;
+
+ comm = (char *) calloc(sizeof(char) * tot_len, '\0');
+ for (i = comm_flag + 1; i < argc; ++i) {
+ sprintf(comm, "%s%s%s", comm, comm[0] == 0 ? "" : " ", argv[i]);
+ }
+
+ return NULL;
+}
+
+void fatal(int status) {
+ if(comm != NULL) {
+ free(comm);
+ }
+
+ exit(status);
+}
+
+void check_config_fatal() {
+ bool ok = true;
+
+ if (file_path == NULL) {
+ fprintf(stderr, "no path provided");
+ ok = false;
+ }
+
+ if (comm == NULL) {
+ fprintf(stderr, "no command provided");
+ ok = false;
+ }
+
+ if (!ok) {
+ fatal(1);
+ }
+}
+
// argv[1]: file path
// argv[2]: command
int main(int argc, char **argv) {
const char *err;
- char *file_path;
int fd;
int wd;
ino_t st_ino;
- if (argc < 3) {
- printf("Usage: run_at_change file_path comm...\n");
- exit(1);
+ // if (argc < 3) {
+ // printf("Usage: run_at_change file_path comm...\n");
+ // fatal(1);
+ // }
+
+ err = load_config(argc, argv);
+
+ if (err != NULL) {
+ fprintf(stderr, "%s\n", err);
+ fatal(1);
}
- file_path = argv[1];
+ check_config_fatal();
printf("monitoring %s\n", file_path);
if (err != NULL) {
fprintf(stderr, "%s\n", err);
- exit(1);
+ fatal(1);
}
if (!reg_file_exists(file_path, &st_ino)) {
fprintf(stderr, "the file %s does not exist\n", file_path);
- exit(1);
+ fatal(1);
}
size_t sz_buf = sizeof(struct inotify_event) + NAME_MAX + 1;
if (err != NULL) {
fprintf(stderr, "%s\n", err);
- exit(1);
+ fatal(1);
}
}
- system(argv[2]);
+ system(comm);
}
}
close_watch(&fd, &wd);
- return fd == 0 ? 1 : 0;
+ fatal(0);
}