您的位置:首页 > 其它

inotify 中, 在 read 其 struct inotify_event 时, 缓冲区必须大于读取的结构体的大小

2012-09-14 16:07 579 查看
linux中监控文件的 inotify 提供了以下几个编程函数, inotify_init(), inotify_add_watch(),

inotify_rm_watch(). 从 inotify_init() 返回的文件描述符 read, 读取监听到的事件.

事件的结构为:

struct inotify_event {
             int      wd;       /* Watch descriptor */
             uint32_t mask;     /* Mask of events */
             uint32_t cookie;   /* Unique cookie associating related
                                   events (for rename(2)) */
             uint32_t len;      /* Size of ’name’ field */
             char     name[];   /* Optional null-terminated name */
         };
因为每个文件名的长度不定, 所以每个事件占用的内存大小也不一定相等.

假设 EVENT_LEN = sizeof(sturct inotify_event), NAME_LEN = len (事件结构体中的len, 为保持内存对齐, 可能大于 strlen(name));

假设inotify的事件队列中有很多未读取的, 读取事件 ret = read(fd, buf, BUF_LEN);

如果 BUF_LEN < EVENT_LEN + NAME_LEN, ret = 0;

如果 EVENT_LEN + NAME_LEN <= BUF_LEN < 2 * (EVENT_LEN + NAME_LEN ), ret = EVENT_LEN + NAME_LEN;

如果 2 * (EVENT_LEN + NAME_LEN) <= BUF_LEN < 3* (EVENT_LEN + NAME_LEN _, ret = 2 * (EVENT_LEN + NAME_LEN );

......

也就是, 只能整个的读取 struct inotify_event, 不能读取部分结构.

- - - - - - - -

以上是我个人的测试.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐