Skip to content

Instantly share code, notes, and snippets.

@Jan200101
Created January 15, 2022 13:14
Show Gist options
  • Select an option

  • Save Jan200101/1d6357e26b1ee20967b0ab42150f16b0 to your computer and use it in GitHub Desktop.

Select an option

Save Jan200101/1d6357e26b1ee20967b0ab42150f16b0 to your computer and use it in GitHub Desktop.
// just throwing shit at the wall
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <libgen.h>
#include <sys/inotify.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
int fd;
int main(int argc, char** argv)
{
char* argv0 = argv[0];
if (argc <= 1)
{
fprintf(stderr, "%s: program [args]\n", argv0);
return 0;
}
char* program = argv[1];
char program_dir[PATH_MAX];
char* program_name = basename(program);
strncpy(program_dir, program, sizeof(program_dir));
dirname(program_dir);
realpath(program_dir, program_dir);
char** args = argv + 1;
fd = inotify_init();
fcntl(fd, F_SETFL, O_NONBLOCK);
puts(program_dir);
inotify_add_watch(fd, program_dir, IN_MODIFY | IN_CREATE);
while (1)
{
pid_t pid = fork();
if (!pid)
{
execvp(program, args);
return 0;
}
else
{
size_t event_size = (strlen(program) + strlen(program_dir) + EVENT_SIZE);
char* event_buffer = (char*)malloc(event_size);
int program_updated = 0;
while(!program_updated)
{
int i = 0;
int length = read(fd, event_buffer, event_size);
while(i < length)
{
struct inotify_event *event = (struct inotify_event *) &event_buffer[i];
if(event->len)
{
if ((event->mask & IN_CREATE ||
event->mask & IN_MODIFY) &&
!(event->mask & IN_ISDIR) &&
!strcmp(event->name, program_name))
{
program_updated = 1;
}
}
i += EVENT_SIZE + event->len;
}
}
sleep(3);
kill(pid, SIGKILL);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment