Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

linux inotify

作者:剑歌踏天下   发布日期:2026-07-02   浏览:34

#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;
}

解释说明:

  1. 创建inotify实例:使用 inotify_init() 函数创建一个新的inotify实例,返回一个文件描述符 fd
  2. 添加监控对象:使用 inotify_add_watch() 函数将指定路径(通过命令行参数传入)添加到监控列表中,并设置监控的事件类型(如修改、创建、删除)。
  3. 读取事件:通过 read() 函数从inotify实例中读取事件。每个事件包含在缓冲区 buffer 中,循环处理这些事件。
  4. 处理事件:根据事件的类型(如 IN_CREATEIN_DELETEIN_MODIFY),输出相应的信息。
  5. 移除监控和关闭实例:当不再需要监控时,使用 inotify_rm_watch() 移除监控,并使用 close() 关闭inotify实例。

该程序会持续监听指定路径下的文件变化,并在控制台输出相应的事件信息。

上一篇:linux rar文件怎么解压

下一篇:linux运行python文件

大家都在看

linux如何启动nginx

linux常用命令查询端口是否正常

linux 发送邮件

linux长ping命令

linux groupadd

linux关机命令行

linux 安装 gcc

linux重启oracle命令

linux把一个文件夹移动到另一个文件夹里

linux查看系统运行时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站