gpt4 book ai didi

c - 将读取与 inotify 一起使用

转载 作者:太空狗 更新时间:2023-10-29 16:36:22 24 4
gpt4 key购买 nike

我一直在研究inotify调用,但是在读取接口(interface)的时候还是有点吃力。这些是我能找到的关于如何使用 read(2) 正确连接 inotify 的最相关资源:

他们都以相同的方式实现它,他们首先定义以下尺寸:

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 )

然后他们以这种方式使用它们:

length = read( fd, buffer, BUF_LEN );  

if ( length < 0 ) {
perror( "read" );
}

while ( i < length ) {
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
/* some processing */
i += EVENT_SIZE + event->len;
}

现在,我们知道 name 是 struct inotify_event 的一部分,并且它的长度是可变的。那么,buffer 中的最后一个 inotify_event 不能被截断吗?

假设有1023个inotify_events,路径为16字节,一个路径为32字节。那么会发生什么?后期会不会被截断?或者内核会发现它不适合缓冲区并完全保留它吗?

最佳答案

基本用法

根据 inotify(7) ,您可以使用 FIONREAD ioctl 找出有多少数据可供读取并相应地调整缓冲区大小。这里有一些(非常粗略的)代码可以完成这个:

unsigned int avail;
ioctl(inotify_fd, FIONREAD, &avail);

char buffer[avail];
read(fd, buffer, avail);

int offset = 0;
while (offset < avail) {
struct inotify_event *event = (inotify_event*)(buffer + offset);

// Insert logic here
my_process_inotify_event(event);

offset = offset + sizeof(inotify_event) + event->len;
}

更健壮的用法

inotify-tools为 inotify 提供更高级别的接口(interface)。您可以使用它来代替访问 inotify,或者您可以查看它如何实现 inotifytools_next_events安全可靠地读取所有可用事件。

部分事件和截断

针对您关于截断的问题,我认为如果给定的缓冲区对于所有事件来说都太小,内核将永远不会返回部分 inotify_event 或截断 inotify_event。 inotify(7) 联机帮助页中的以下段落表明了这一点:

The behavior when the buffer given to read(2) is too small to return information about the next event depends on the kernel version: in kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2) fails with the error EINVAL.

来自 inotifytools.c 的以下评论也是如此:

// oh... no.  this can't be happening.  An incomplete event.
// Copy what we currently have into first element, call self to
// read remainder.
// oh, and they BETTER NOT overlap.
// Boy I hope this code works.
// But I think this can never happen due to how inotify is written.

关于c - 将读取与 inotify 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com