EDIT:我最后使用了inotify。正如 stefanB 所说,inotify 是最适合使用的东西。我发现了一个尾部克隆,它使用inotify来实现-f模式,inotail http://distanz.ch/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()
下一个代码位于 file.txt 的 eof 后面(由上面的代码更新)
# tail -f
from time import *
file = open("file.txt", "r")
file.seek(0, 2)
while 1:
line = file.readline()
if not line:
sleep(1)
else:
print line
file.close()
一切正常,但 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() 代替所提出的解决方案来实现它是一个好主意吗?
提前致谢。