Skip to content

Instantly share code, notes, and snippets.

@furandon-pig
Created December 8, 2021 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furandon-pig/761cb5a234c6419d153c39b62bd22097 to your computer and use it in GitHub Desktop.
Save furandon-pig/761cb5a234c6419d153c39b62bd22097 to your computer and use it in GitHub Desktop.
NetBSDのfilemon機能を使用してファイルの変更イベントを監視するサンプルプログラムです。
#include <stdio.h>
#include <stdlib.h>
#include <dev/filemon/filemon.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid;
int filemon_fd, temp_fd;
int status;
char temp_path[] = "/tmp/filemonXXXXXXXX";
filemon_fd = open("/dev/filemon", O_RDWR);
temp_fd = mkstemp(temp_path);
// give filemon the temp file to use
ioctl(filemon_fd, FILEMON_SET_FD, &temp_fd);
// children do not need these one they exec
fcntl(filemon_fd, F_SETFD, FD_CLOEXEC);
fcntl(temp_fd, F_SETFD, FD_CLOEXEC);
pid = fork();
switch(pid) {
case -1:
fprintf(stderr, "cannot fork");
break;
case 0:
pid = getpid();
printf("pid= %d\n", pid);
printf("filemon= %s\n", temp_path);
// tell filemon to monitor this process
ioctl(filemon_fd, FILEMON_SET_PID, &pid);
char *args[] = { "/usr/pkg/bin/bash", NULL };
execvp("/usr/pkg/bin/bash", args);
_exit(1);
break;
default:
wait(&status);
close(filemon_fd);
lseek(temp_fd, SEEK_SET, 0);
// read the captured syscalls from temp_fd
close(temp_fd);
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment