C 使用inotify优化程序
我通过inotify编写了一个程序来检查循环中的文件更改,以获取对该文件的任何更改。 但我认为这可以做得更好。 有人能写得更好吗C 使用inotify优化程序,c,linux,inotify,C,Linux,Inotify,我通过inotify编写了一个程序来检查循环中的文件更改,以获取对该文件的任何更改。 但我认为这可以做得更好。 有人能写得更好吗 #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <linux/inotify.h> #include <sys/select.h> #define EVENT_SIZ
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>
#include <sys/select.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int event_check (int fd)
{
fd_set rfds;
FD_ZERO (&rfds);
FD_SET (fd, &rfds);
/* Wait until an event happens or we get interrupted
by a signal that we catch */
return select (FD_SETSIZE, &rfds, NULL, NULL, NULL);
}
int main( )
{
int length, i = 0;
int fd;
int wd;
while(1){
i=0;
fd = inotify_init();
if ( fd < 0 ) {
perror( "inotify_init" );
}
wd = inotify_add_watch( fd, "/tmp/test", IN_CLOSE_WRITE);
if (event_check (fd) > 0)
{
char buffer[EVENT_BUF_LEN];
int count = 0;
length = read( fd, buffer, EVENT_BUF_LEN );
if ( length < 0 ) {
perror( "read" );
}
while ( i < length ) { struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
printf( "New file %s Editted.\n", event->name );
i += EVENT_SIZE + event->len;
}
}
}
inotify_rm_watch( fd, wd );
close( fd );
}
#包括
#包括
#包括
#包括
#包括
#包括
#定义事件大小(sizeof(结构索引事件))
#定义事件大小(1024*(事件大小+16))
int事件检查(int fd)
{
fd_集rfds;
FD_ZERO(和RFD);
FD_集(FD和RFD);
/*等待事件发生或我们被打断
通过我们捕捉到的信号*/
返回select(FD_SETSIZE,&rfds,NULL,NULL,NULL);
}
int main()
{
整数长度,i=0;
int-fd;
int-wd;
而(1){
i=0;
fd=inotify_init();
如果(fd<0){
perror(“inotify_init”);
}
wd=inotify\u add\u watch(fd,“/tmp/test”,在\u CLOSE\u WRITE中);
如果(事件检查(fd)>0)
{
字符缓冲区[EVENT_BUF_LEN];
整数计数=0;
长度=读取(fd、缓冲区、事件长度);
如果(长度<0){
佩罗(“阅读”);
}
而(i名称);
i+=事件大小+事件->镜头;
}
}
}
inotify_rm_手表(fd、wd);
关闭(fd);
}
我从未使用过inotify,因此这可能是错误的,但我认为以下几个更改可能会“改进”您的代码
inotify\u init
或inotify\u add\u watch
放入循环中。只需在循环之前进行一次初始化工作事件检查
函数。您没有指定超时,并且只使用一个文件描述符,因此我认为read将为您提供相同的功能性我认为一个程序只需要一个inotify_init,一个目录只需要一个inotify_add_watch。
你能粘贴你说不起作用的“init和add_watch out the loop”版本吗?你能定义一下你希望代码更好的意思吗?在哪些方面更好?我能写得更好吗?很可能。你有什么特别想要的吗?只要正确地重新定义代码就会使它“更好”。同时在select中去掉FD_SETSIZE。