我有代码来监听目录中的更改, 当我运行它时,文件中的任何内容都不会在终端上显示出来。
任何人都可以帮助我听听特定文本文件中发生的变化吗?我想存储时间戳以及发生了什么变化。
代码是:
/*This is the sample program to notify us for the file creation and file deletion takes place in “/tmp” directory*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int main( )
{
int length, i = 0;
int fd;
int wd;
char buffer[EVENT_BUF_LEN];
char str[] = "This is tutorialspoint.com";
FILE* fp=NULL;;
fp=fopen("f1.txt","rw+");
/*creating the INOTIFY instance*/
fd = inotify_init();
/*checking for error*/
if ( fd < 0 ) {
perror( "inotify_init" );
}
/*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
wd = inotify_add_watch( fd, "/tmp", IN_CREATE | IN_DELETE );
/*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/
length = read(fd, buffer, EVENT_BUF_LEN );
/*checking for error*/
if ( length < 0 ) {
perror( "read" );
}
/*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
while ( i < length ) { struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; if ( event->len ) {
if ( event->mask & IN_CREATE ) {
if ( event->mask & IN_ISDIR ) {
printf( "New directory %s created.1\n", event->name );
fwrite(str , 1 , sizeof(str) , fd );
}
else {
printf( "New file %s created.\n2", event->name );
fwrite(str , 1 , sizeof(str) , fd );
}
}
else if ( event->mask & IN_DELETE ) {
if ( event->mask & IN_ISDIR ) {
fwrite(str , 1 , sizeof(str) , fd );
printf( "Directory %s deleted.\n", event->name );
}
else {
printf( "File %s deleted.\n", event->name );
}
}
}
i += EVENT_SIZE + event->len;
}
/*removing the “/tmp” directory from the watch list.*/
inotify_rm_watch( fd, wd );
fclose(fd);
/*closing the INOTIFY instance*/
close( fd );
}
答案 0 :(得分:1)
我的猜测是,它只会阻止read
来电。从上面的评论:
实际上,这个读取会阻止,直到发生更改事件
您正在等待的任何事件都没有发生,此read
来电将会阻止,直到有。{/ p>
我建议你在一个终端运行这个程序,而在另一个终端运行,例如。
$ touch /tmp/foo