编辑:我最后使用了inotify。正如stefanB所说,inotify是一个可以使用的东西。我发现了一个尾部克隆,它使用inotify实现-f模式inotail。在
原始问题文本:
我试图在一个C项目中实现“tail-f”逻辑,为了原型化,我用python开发了它,如下所示:
# A forever loop, each 5 seconds writes a line into file.txt
from time import *
while 1:
sleep(5)
file = open("file.txt", "a")
file.write("This is a test\n")
file.close()
下一个代码遵循文件.txt(以上代码更新)
^{pr2}$所有的工作都很好,但是C实现不工作(没有检查错误代码)。省略了stdio.h、string.h和unistd.h的包含(彩色化隐藏了头包含代码)。在
#define LINE_LEN 256
int main(int argc, char **argv)
{
FILE *f;
char line[LINE_LEN];
f = fopen("file.txt", "r");
fseek(f, 0, SEEK_END);
while (1)
{
fgets(line, LINE_LEN, f);
if (strlen(line) == 0)
{
sleep(1);
}
else
{
printf("Readed: %s", line);
}
}
fclose(f);
return 0;
}
有什么想法吗?在
用poll()而不是呈现的解决方案来实现它是个好主意吗?。在
提前谢谢。在
编辑: 似乎inotify是要使用的东西。从2.6.13开始,它应该包含在linux内核中。An article from IBM developerworks about inotify。在
上一个答案:
看看Linux File Alteration Monitor(在Linux内核2.4.x>;)中。它是一个框架,允许您订阅文件更改,并在更改发生时从内核获得回调。这应该比投票更好。在
Examples如何轮询文件更改,请查看等待文件更改的部分和轮询文件更改。在
我还没试过。在
一旦文件*发现错误或eof,它就设置了其内部状态,以便在后续调用中继续返回error或eof。在睡眠返回后,您需要调用
clearerr(f);
,以清除eof设置并让它尝试从文件中读取更多数据。在来自
tail
man page:所以,你可以做同样的事情:
相关问题 更多 >
编程相关推荐