使用inotify监控文件 [英] Monitoring file using inotify

查看:219
本文介绍了使用inotify监控文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用inotify来监视本地文件,例如/ root / temp,使用inotify_add_watch(fd,/ root / temp,mask)。当这个文件被删除时,程序将被读(fd,buf,bufSize)函数阻塞。即使我创建了一个新的/ root / temp文件,程序仍然被读取函数阻塞。我想知道ifotify是否可以检测到被监控的文件被创建,并且读取函数可以从fd获取东西,以便读取不会被永远阻止。
这是我的代码:

  uint32_t mask = IN_ALL_EVENTS; 
int fd = inotify_init();
int wd = inotify_add_watch(fd,/ root / temp,mask);
char * buf = new char [1000];
int nbytes = read(fd,buf,500);

我监控所有活动。



解决方案

问题是



如果您不想阻止它,请使用之前选择 poll 。例如:

  struct pollfd pfd = {fd,POLLIN,0} 
int ret = poll(& pfd,1,50); // timeout of 50ms
if(ret< 0){
fprintf(stderr,poll failed:%s\\\
,strerror(errno));
} else if(ret == 0){
//超时没有事件,继续。
} else {
//处理新事件。
struct inotify_event event;
int nbytes = read(fd,& event,sizeof(event));
//做你需要的...
}

注意:未测试的代码。


I am using inotify to monitor a local file, for example "/root/temp" using inotify_add_watch(fd, "/root/temp", mask). When this file is deleted, the program will be blocked by read(fd, buf, bufSize) function. Even if I create a new "/root/temp" file, the program is still block by read function. I am wondering if inotify can detect that the monitored file is created and the read function can get something from fd so that read will not be blocked forever. Here is my code:

uint32_t mask = IN_ALL_EVENTS;
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/root/temp", mask);
char *buf = new char[1000];
int nbytes = read(fd, buf, 500);

I monitored all events.

Thank you very much.

cheng

解决方案

The problem is that read is a blocking operation by default.

If you don't want it to block, use select or poll before read. For example:

struct pollfd pfd = { fd, POLLIN, 0 };
int ret = poll(&pfd, 1, 50);  // timeout of 50ms
if (ret < 0) {
    fprintf(stderr, "poll failed: %s\n", strerror(errno));
} else if (ret == 0) {
    // Timeout with no events, move on.
} else {
    // Process the new event.
    struct inotify_event event;
    int nbytes = read(fd, &event, sizeof(event));
    // Do what you need...
}

Note: untested code.

这篇关于使用inotify监控文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆