软件开发: 03 2010存档

需要监控某个目录下有没有文件增加或删除,当然不能用循环检测来做,那样太耗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,用不了;即使用得了,上诉第二个问题也是无法解决的。所以最后只能自己写驱动。