我正在编写一个程序来监视何时使用C ++将文件写入Mac OSX文件系统。我直接调用fsevents,这样我就可以获得将文件写入文件系统的进程的PID。
当我在用户名下运行程序时,我收到错误" kevent寄存器:错误的文件描述符"属于我的计划的第43行。如果我以sudo身份运行它,程序运行时没有错误,但从未收到写入文件的通知。我通过发出:echo "blah" >> /tmp/1234
来测试它。
代码:
#include "fcntl.h" //for O_RDONLY
#include "errno.h" //for errno
#include "stdio.h" //for fprintf()
#include "string.h" //for strerror()
#include "stdlib.h" //for EXIT_SUCCESS
#include "sys/event.h" //for kqueue() & more
#include "unistd.h" //for close()
#include <err.h>
#include <sys/ioctl.h> //for iotcl control working with fsevents
int main(int argc, char *argv[])
{
printf("Exectuted");
struct kevent kev_set; /* Event we want to monitor */
struct kevent kev_retr; /* Event triggered */
int kq, fd, ret;
// directory to monitor, NO checks for errors here
fd = open ("/dev/fsevents", O_RDONLY);
//if (ioctl(fd, TIOCMGET, &status) >= 0)
// err(EXIT_FAILURE, "TIOCMGET failed:");
kq = kqueue();
if (kq == -1)
err(EXIT_FAILURE, "kqueue() failed");
/* Initialize kevent structure. */
EV_SET(&kev_set, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL);
/* Attach event to the kqueue. */
ret = kevent(kq, &kev_set, 1, NULL, 0, NULL);
if (ret == -1)
err(EXIT_FAILURE, "kevent register");
for (;;) {
/* Sleep until something happens */
printf("Starting loop\n");
ret = kevent(kq, NULL, 0, &kev_retr, 1, NULL);
if (ret == -1)
{
err(EXIT_FAILURE, "kevent wait");
}
else if (ret > 0) {
printf("Something was written: ");
}
}
close(fd);
}
输出:
$ ./fsmon-test
fsmon-test: kevent register: Bad file descriptor
提前谢谢!