Comment detail

ファイル更新の監視 (Nested Flatten)
tail -f の動作を調べて、参考にしました。
kevent, kqueue を使っているので BSD 限定だと思います。
簡単のためファイル名変更と削除には対応していません。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/event.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>


int main ( int argc, char *argv[] ){

   struct stat sb;
   struct kevent kev;
   int kq, fd;


   if( argc < 2 ){
      fprintf(stderr,"Usage: %s filename\n", argv[0] );
      return EXIT_FAILURE;
   }

   if( stat( argv[1], &sb ) == -1 ){
      fprintf(stderr,"%s is not acceessible\n", argv[1] );
      return EXIT_FAILURE;
   }

   if( !S_ISREG( sb.st_mode ) ){
      fprintf(stderr,"%s is not regular file\n", argv[1] );
      return EXIT_FAILURE;
   }

   if( (fd = open( argv[1], O_RDONLY )) == -1 ){
      fprintf(stderr,"open(\"%s\") failed\n", argv[1] );
      return EXIT_FAILURE;
   }

   kq = kqueue();

   EV_SET( &kev, fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR , 0, 0, 0 );
   if( kevent(kq, &kev, 1, NULL, 0, NULL) < 0 ){
      fprintf(stderr,"kevent failed\n" );
      return EXIT_FAILURE;
   }
   while(1){
      kevent(kq, NULL, 0, &kev, 1, NULL);
      printf("modified!\n");
   }
   return EXIT_SUCCESS;
}
プラス評価ありがとうございます。
- 初回のイベント通知は捨てる。
- close 処理を追加。
を追加してみました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
--- main.c.org  Thu Nov 15 23:18:57 2007
+++ main.c      Thu Nov 15 23:23:17 2007
@@ -4,7 +4,13 @@
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>

+int received_sigint;
+void sigint_handler( int sig ){
+   received_sigint = 1;
+}

 int main ( int argc, char *argv[] ){

@@ -33,6 +39,11 @@
       return EXIT_FAILURE;
    }

+   if( signal(SIGINT, sigint_handler) == SIG_ERR ){
+      fprintf(stderr,"couldn't register SIGINT handler\n");
+      return EXIT_FAILURE;
+   }
+
    kq = kqueue();

    EV_SET( &kev, fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR , 0, 0, 0 );
@@ -40,9 +51,16 @@
       fprintf(stderr,"kevent failed\n" );
       return EXIT_FAILURE;
    }
+   kevent(kq, NULL, 0, &kev, 1, NULL);
    while(1){
-      kevent(kq, NULL, 0, &kev, 1, NULL);
+      if( kevent(kq, NULL, 0, &kev, 1, NULL) == -1 ){
+         if( !received_sigint ){
+            perror("error");
+         }
+         break;
+      }
       printf("modified!\n");
    }
+   close(fd);
    return EXIT_SUCCESS;
 }

Index

Feed

Other

Link

Pathtraq

loading...