#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUFFER_SIZE ( 1024 * ( EVENT_SIZE + 16 ) )
int main( int argc, char **argv ) {
int length, i = 0;
int fd;
int wd;
char buffer[ BUFFER_SIZE ];
// 创建inotify实例
fd = inotify_init();
if ( fd < 0 ) {
perror( "inotify_init" );
exit( EXIT_FAILURE );
}
// 添加要监控的文件或目录
wd = inotify_add_watch( fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE );
if ( wd < 0 ) {
perror( "inotify_add_watch" );
exit( EXIT_FAILURE );
}
printf("Listening for changes in %s\n", argv[1]);
// 循环读取事件
while (1) {
length = read( fd, buffer, BUFFER_SIZE );
if ( length < 0 ) {
perror( "read" );
exit( EXIT_FAILURE );
}
i = 0;
while ( i < length ) {
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
if ( event->len ) {
if ( event->mask & IN_CREATE ) {
printf( "File %s was created.\n", event->name );
} else if ( event->mask & IN_DELETE ) {
printf( "File %s was deleted.\n", event->name );
} else if ( event->mask & IN_MODIFY ) {
printf( "File %s was modified.\n", event->name );
}
}
i += EVENT_SIZE + event->len;
}
}
// 移除监控并关闭inotify实例
inotify_rm_watch( fd, wd );
close( fd );
return 0;
}
inotify_init() 函数创建一个新的inotify实例,返回一个文件描述符 fd。inotify_add_watch() 函数将指定路径(通过命令行参数传入)添加到监控列表中,并设置监控的事件类型(如修改、创建、删除)。read() 函数从inotify实例中读取事件。每个事件包含在缓冲区 buffer 中,循环处理这些事件。IN_CREATE、IN_DELETE、IN_MODIFY),输出相应的信息。inotify_rm_watch() 移除监控,并使用 close() 关闭inotify实例。该程序会持续监听指定路径下的文件变化,并在控制台输出相应的事件信息。
上一篇:linux rar文件怎么解压
下一篇:linux运行python文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站