利用inotify监测文件是否被修改,并利用fork和execl调用脚本

监测/root/a.log是否被修改,被修改则调用脚本/root/a.sh

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <sys/select.h>
#include <errno.h>

#define EVENT_SIZE (sizeof (struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
#define TRUE 1
#define PATH "/root/a.log"

int main()
{
    int wd = 0;
    int fd = 0;
    int ret = 0;
    char buf[BUF_LEN] = {0};
    char *script_path = "/root/a.sh";
    char *p;
    struct inotify_event *event;
    pid_t pid;

    fd = inotify_init();
    if(fd < 0)  
    {  
        // printf("inotify_init error!\n");  
        return 0;  
    }
    // printf("fd=%d\n",fd);

    wd = inotify_add_watch(fd,PATH,IN_MODIFY);//don't use IN_ALL_EVENTS
    
    if(wd < 0)  
    {  
        // printf("inotify_add_watch error!\n");  
        return 0;  
    }
    // printf("wd=%d\n",wd);

    while(TRUE)
    {
        ret = read(fd,&buf,sizeof(buf));

        if(ret < 0)
        {
            // printf("read error!\n");  
            return 0; 
        }

        for(p = buf;p < buf + ret;)
        {
            event = (struct inotify_event *) p;
            if(event->mask & IN_MODIFY)
            {
                // execl("/bin/sh","sh","-pc",script_path,NULL);
                pid = fork();
                
                if(pid < 0)
                {
                    return 0;
                }
                else if(pid == 0)
                {
                    // printf("child\n");
                    execl("/bin/sh","sh","-pc",script_path,NULL);
                    exit(0);
                }
                else
                {
                    wait();
                    // printf("father\n");
                }
            }
            p += sizeof(struct inotify_event) + event->len;
        }
    }
    inotify_rm_watch(fd,wd);
    close(fd);
    return 0;
}

/root/a.sh

echo "file changed"

转载于:https://www.cnblogs.com/emrysche/articles/9354388.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值