Monitoring file using inotify

喜欢而已 提交于 2019-12-03 03:31:53

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.

In order to see a new file created, you need to watch the directory, not the file. Watching a file should see when it is deleted (IN_DELETE_SELF) but may not spot if a new file is created with the same name.

You should probably watch the directory for IN_CREATE | IN_MOVED_TO to see newly created files (or files moved in from another place).

Some editors and other tools (e.g. rsync) may create a file under a different name, then rename it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!