我正在尝试编写一个“简单”版本的Dropbox。因此,我需要以某种方式监视指定的目录。我选择了inotify系统调用来处理此问题,但是我遇到了问题。每当我在终端上进行修改/删除/创建时,都可以。但是,当我在GUI上进行更改时,比如说通过gedit,会显示不同的消息。这是一个错误如何工作的示例:
对于那些无法显示图像的人,通知是“创建了新文件.goutputstream-46LT1Z”。而不是“ modify.c已修改”。 修改后的文件名为modify.c,但通知如下:文件名错误,操作错误(已修改,未创建)
这是我从https://www.thegeekstuff.com/2010/04/inotify-c-program-example/网站获取的代码:
/*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];
/*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.\n", event->name );
}
else {
printf( "New file %s created.\n", event->name );
}
}
else if ( event->mask & IN_DELETE ) {
if ( event->mask & IN_ISDIR ) {
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 );
/*closing the INOTIFY instance*/
close( fd );
}
我陷入了困境,非常感谢事先提供的帮助!