我是狂热的新手。
我使用 fanotify 手册页的示例将任何信息写入文件,同时处理文件打开和关闭的事件。对“fopen”的系统调用导致系统挂起。当我将“FAN_OPEN_PERM”更改为“FAN_OPEN”时,一切正常,但“FAN_OPEN_PERM”标志不允许记录文件。
有什么我错过了使用 fanotify 技术的地方吗?或者处理 fanotify 存在任何限制?
或者在处理 fanotify 事件时记录文件的任何更好的想法?
我已经在 'Ubuntu 14.04.3 64bit' 和 '3.16.0-70-generic' 内核版本下编译和测试。
我添加了一些这样的代码:
static void PrintToFile(const char *pszMsg)
{
int err = 0;
if( NULL == pszMsg) {
printf("invalid message\n");
return ;
}
FILE *fp = fopen("/tmp/fanotify.log", "a+"); // <= here, system hangs
if( NULL == fp ) {
err = errno;
printf("file open fail ( %d ) \n", err);
return ;
}
size_t len = strlen(pszMsg);
feesk(fp, 0L, SEEK_END );
fwrite(pszMsg, 1, len, fp);
fclose(fp);
}
然后,我将下一个代码添加到“handle_events”函数中
{
char strBuf[PATH_MAX];
sprintf(strBuf, "File %s\n", path);
PrintToFile(strBuf);
}
查看修改后的“handle_events”函数
static void
handle_events(int fd)
{
const struct fanotify_event_metadata *metadata;
struct fanotify_event_metadata buf[200];
ssize_t len;
char path[PATH_MAX];
ssize_t path_len;
char procfd_path[PATH_MAX];
struct fanotify_response response;
/* Loop while events can be read from fanotify file descriptor */
for(;;) {
/* Read some events */
len = read(fd, (void *) &buf, sizeof(buf));
if (len == -1 && errno != EAGAIN) {
perror("read");
exit(EXIT_FAILURE);
}
/* Check if end of available data reached */
if (len <= 0)
break;
/* Point to the first event in the buffer */
metadata = buf;
/* Loop over all events in the buffer */
while (FAN_EVENT_OK(metadata, len)) {
/* Check that run-time and compile-time structures match */
if (metadata->vers != FANOTIFY_METADATA_VERSION) {
fprintf(stderr,
"Mismatch of fanotify metadata version.\n");
exit(EXIT_FAILURE);
}
/* metadata->fd contains either FAN_NOFD, indicating a
queue overflow, or a file descriptor (a nonnegative
integer). Here, we simply ignore queue overflow. */
if (metadata->fd >= 0) {
/* Handle open permission event */
if (metadata->mask & FAN_OPEN_PERM) {
printf("FAN_OPEN_PERM: ");
/* Allow file to be opened */
response.fd = metadata->fd;
response.response = FAN_ALLOW;
write(fd, &response,
sizeof(struct fanotify_response));
}
/* Handle closing of writable file event */
if (metadata->mask & FAN_CLOSE_WRITE)
printf("FAN_CLOSE_WRITE: ");
/* Retrieve and print pathname of the accessed file */
snprintf(procfd_path, sizeof(procfd_path),
"/proc/self/fd/%d", metadata->fd);
path_len = readlink(procfd_path, path,
sizeof(path) - 1);
if (path_len == -1) {
perror("readlink");
exit(EXIT_FAILURE);
}
path[path_len] = '\0';
printf("File %s\n", path);
//these code snipptets are added
{
char strBuf[PATH_MAX];
sprintf(strBuf, "File %s\n", path);
PrintToFile(strBuf);
}
/* Close the file descriptor of the event */
close(metadata->fd);
}
/* Advance to next event */
metadata = FAN_EVENT_NEXT(metadata, len);
}
}
}