use*_*138 6 c++ linux file-descriptor nonblocking inotify
我使用inotify监视本地文件,例如"/ root/temp"使用
inotify_add_watch(fd, "/root/temp", mask).
Run Code Online (Sandbox Code Playgroud)
删除此文件时,程序将被read(fd, buf, bufSize)功能阻止.即使我创建了一个新的"/ root/temp"文件,程序仍然被读取函数阻塞.我想知道inotify是否可以检测到已创建受监视文件,并且读取函数可以从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);
Run Code Online (Sandbox Code Playgroud)
我监控了所有事件.
jwe*_*ich 20
问题是read默认情况下是阻塞操作.
如果您不希望它阻止,使用select或poll之前read.例如:
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...
}
Run Code Online (Sandbox Code Playgroud)
注意:未经测试的代码.