[linux] 文件通知机制 (dnotify, inotify)

需要监控某个目录下有没有文件增加或删除,当然不能用循环检测来做,那样太耗CPU,所以改用2.6.9内核支持的dir notify机制,查了一下例子:


        #define _GNU_SOURCE     /* needed to get the defines */

        #include <fcntl.h>      /* in glibc 2.2 this has the needed

                                           values defined */

        #include <signal.h>

        #include <stdio.h>

        #include <unistd.h>


        static volatile int event_fd;


        static void handler(int sig, siginfo_t *si, void *data)

        {

                event_fd = si->si_fd;

        }


        int main(void)

        {

                struct sigaction act;

                int fd;


                act.sa_sigaction = handler;

                sigemptyset(&act.sa_mask);

                act.sa_flags = SA_SIGINFO;

                sigaction(SIGRTMIN + 1, &act, NULL);


                fd = open(".", O_RDONLY);

                fcntl(fd, F_SETSIG, SIGRTMIN + 1);

                fcntl(fd, F_NOTIFY, DN_MODIFY|DN_CREATE|DN_MULTISHOT);

                /* we will now be notified if any of the files

                   in "." is modified or new files are created */

                while (1) {

                        pause();

                        printf("Got event on fd=%d\n", event_fd);

                }

        }


我试着在项目里用了一下,发现不行,有两个大毛病:

1. 信号机制会打断程序运行,epoll调用也会被打断,虽然还能“续上”,但毕竟影响太大

2. dnotify机制通知很快,我的创建文件后初始数据还没写进去,监控程序就发现并打开了文件


inotify是2.6.12才开始引入内核,而我用的是rhel4,用不了;即使用得了,上诉第二个问题也是无法解决的。所以最后只能自己写驱动。


相关文章

分类

留言:

关于文章

This page contains a single entry by DongHao published on 03 2, 2010 5:57 PM.

“852号”的故事 was the previous entry in this blog.

[linux-kernel] 实现支持poll的驱动设备 is the next entry in this blog.

Find recent content on the main index or look in the 存档 to find all content.