利用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"
posted @ 2018-07-23 14:12  EmrysChe  阅读(573)  评论(0编辑  收藏  举报