Skip to content

Instantly share code, notes, and snippets.

@elazarl
Created Nov 29, 2017
Embed
What would you like to do?
constantly polls until a file disappears
#include <argp.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
static char args_doc[] = "FILES to poll until missing";
static char doc[] = "poll for a file until it doesn't exist";
static error_t parse_opt(int key, char *arg, struct argp_state *state);
static struct argp_option options[] = {{0}};
static struct argp argp = {options, parse_opt, args_doc, doc, NULL, NULL, NULL};
#define ARRAYSIZE(x) ((sizeof(x)) / (sizeof(x[0])))
struct arguments {
int nfiles;
char *files[1000];
};
void clean_arguments(struct arguments *args) { free(args->files); }
int main(int argc, char **argv) {
struct arguments __attribute__((__cleanup__(clean_arguments)))
args = {};
argp_parse(&argp, argc, argv, 0, 0, &args);
for (;;) {
int i;
for (i = 0; i < args.nfiles; i++) {
int fd = open(args.files[i], O_RDONLY);
if (fd > 0) {
close(fd);
continue;
}
if (errno == ENOENT) {
printf("file %s does not exist\n",
args.files[i]);
exit(0);
}
}
}
}
const char *argp_program_version = "checkexist 1.0";
const char *argp_program_bug_address = "<elazarl@gmail.com>";
/* Program documentation. */
static error_t parse_opt(int key, char *arg, struct argp_state *state) {
/* Get the input argument from argp_parse, which we
* know is a pointer to our arguments structure. */
struct arguments *arguments = state->input;
switch (key) {
case ARGP_KEY_ARG:
if (state->arg_num >=
ARRAYSIZE(
arguments->files)) /* Too many arguments. */
argp_usage(state);
arguments->files[state->arg_num] = arg;
break;
case ARGP_KEY_END:
if (state->arg_num < 1) /* Not enough arguments. */
argp_usage(state);
arguments->nfiles = state->arg_num;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment