Monitoring file using inotify

后端 未结 2 2041
-上瘾入骨i
-上瘾入骨i 2021-02-06 11:33

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 de

2条回答
  •  故里飘歌
    2021-02-06 12:10

    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.

提交回复
热议问题