gpt4 book ai didi

c - inotify api 在报告一两次后停止工作

转载 作者:行者123 更新时间:2023-12-02 03:23:12 24 4
gpt4 key购买 nike

我想测试inotify,所以从互联网上拿了几个例子,对其进行修改以学习各个方面,但失败了,因为它没有像我想要的那样工作。首先,我尝试监视一个运行良好的目录。

所以我通过一些修改扩展了该文件的示例,但它只能工作一次,并且在读取功能时被阻止

#include <sys/inotify.h>
#include <unistd.h>
#include <stdio.h>

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

int main()
{
int fd;
fd = inotify_init();
if (fd < 0)
perror("inotify_init()");
int wd;
wd = inotify_add_watch(fd, "target", IN_CLOSE_WRITE);
if (wd < 0)
perror("inotify_add_watch");

char buf[BUF_LEN];
int len;

while(1) {

len = read(fd, buf, BUF_LEN);

printf("after read\n");

if (len > 0)
{
int i = 0;
while (i < len)
{
struct inotify_event *event;
event = (struct inotify_event *) &buf[i];

printf("wd=%d mask=%x cookie=%u len=%u\n",
event->wd, event->mask,
event->cookie, event->len);

if (event->mask & IN_MODIFY)
printf("file modified %s", event->name);

if (event->len)
printf("name=%s\n", event->name);

i += EVENT_SIZE + event->len;
}
}

}

return 0;
}

所以,我转向 select(),但在这里,它也工作一次,报告两次,然后停止报告更改。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>

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

int main( int argc, char **argv )
{
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];

struct timeval timeout;

fd = inotify_init();

if ( fd < 0 ) {
perror( "inotify_init" );
}

wd = inotify_add_watch( fd, "target",
IN_CLOSE_WRITE );
fd_set rfds,rfdss;
int ret;

/* zero-out the fd_set */
FD_ZERO (&rfds);
FD_ZERO (&rfdss);
FD_SET (fd, &rfds);

timeout.tv_sec = 5;
timeout.tv_usec = 0;

while(1){
printf("Before select\n");
//rfds = rfdss;
ret = select (fd + 1, &rfds, NULL, NULL, NULL);
printf("After Select\n");
timeout.tv_sec = 5;
timeout.tv_usec = 0;
if (ret < 0)
perror ("select");
else if (!ret){
}
/* timed out! */
else if (FD_ISSET (fd, &rfds)){
printf("file changed============\n");
length = read( fd, buffer, BUF_LEN );
}
}

( void ) inotify_rm_watch( fd, wd );
( void ) close( fd );

exit( 0 );
}

最佳答案

一些研究表明,流行的编辑器以不同的方式保存它。

他们实际上不是直接覆盖该文件,而是创建一个临时文件,然后用新的临时文件替换原始文件。因此,实际发生的情况是您实际观看的文件不再存在,因此所做的任何更改都不会反射(reflect)回来。

实际遵循此方法的编辑器是(可能存在更多)Gedit、Geany、vi

直接覆盖文件的编辑器是(可能存在更多)纳米

因此,即使代码是正确的,编辑器的异常行为也可能会出现问题

关于c - inotify api 在报告一两次后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24575705/

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