linux 监听新文件

#include <sys/inotify.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define INOTIFY_EVENT_ARR_SIZE (1024)

int main(int argc, char *argv[])
{
    const char *installlist_path = "/tmp";

    int fd, wd, count = 5;
    struct inotify_event eventArr[INOTIFY_EVENT_ARR_SIZE];
    int eventSize = sizeof(struct inotify_event);
    int eventArrSize = eventSize * INOTIFY_EVENT_ARR_SIZE;

    do {
        if ((fd = inotify_init()) < 0) {
            printf("Open file descriptor fail\n");
            continue;
        }  

        if ((wd = inotify_add_watch(fd, installlist_path, IN_CREATE | IN_MOVED_TO)) < 0) {
        	printf("Inotify add watch fail\n");
            close(fd);
            continue;
        }
        break;
    } while (count--);

    if (count < 0) {
    	printf("exit\n");
        return -1;
    }

    while (1) {
        memset(eventArr, 0x00, eventArrSize);
        int readLen = read(fd, eventArr, eventArrSize);
        if(readLen <= 0) {
        	printf("Read fail ( Check whether it is interrupted by signal\n");
            sleep(1);
            continue;
        }

        int size = readLen / eventSize;
        for (int i = 0; i < size; ++i) {
            if (eventArr[i].len && (eventArr[i].mask & IN_CREATE)) {
                printf("%s/%s\n", installlist_path, eventArr[i].name);
                i += (
                        (eventArr[i].len % eventSize) ? 
                        (eventArr[i].len / eventSize + 1) : 
                        (eventArr[i].len / eventSize)
                    );
            }
        }
    }
    close(fd);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux系统中,可以通过inotify机制进行文件监控。inotify是Linux系统提供的一种文件系统监控工具,它可以监听文件系统事件,如文件或目录的创建、修改、删除等。 要实现文件复制的监听,在Linux系统中可以使用inotify-tools工具包提供的inotifywait命令,它可以监视指定目录的文件系统事件,并在事件发生时做出相应的响应。 在使用inotifywait命令时,需要指定要监视的目录及其事件类型,例如: ```bash inotifywait -m /path/to/directory -e create -e moved_to -e modify ``` 这个命令将监视/path/to/directory目录中文件的创建、移动和修改事件。当这些事件发生时,inotifywait会打印出相应的信息,如文件名、事件类型等。 接下来,可以编写脚本来对复制文件进行监听,并在文件复制完成后做出相应的操作,例如发送邮件通知、记录日志等。例如,以下是一个简单的脚本示例: ```bash #!/bin/bash inotifywait -m /path/to/source_dir -e create | while read path action file; do if [[ "$file" =~ .*\.txt$ ]]; then cp "$path$file" /path/to/target_dir echo "File $file copied to target directory" >> /path/to/log_file echo "File $file copied to target directory" | mail -s "File copied" user@example.com fi done ``` 这个脚本将监视/path/to/source_dir目录中的文件创建事件,并对以.txt结尾的文件进行复制。在文件复制完成后,它会记录日志、发送邮件通知等操作。 总而言之,通过inotify机制可以在Linux系统中实现文件复制的监听,从而自动化管理文件复制过程,增强系统的可靠性与稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值