定制实施"尾-f"在C功能的 [英] Custom implementation of "tail -f" functionality in C
问题描述
编辑:我用,最后,inotify的。作为stefanB说inotify的是使用的东西。我发现,使用的inotify实现-f模式尾克隆, inotail 。
I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, inotail.
原来的问题文本:
我想实现一个C项目的尾-f的逻辑,对样机的目的我开发它在python如下:
I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow:
# 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()
接下来的code如下file.txt的的EOF(由上面的code更新)
The next code follows the eof of file.txt (updated by the code above)
# 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实现不工作(有没有检查错误code)。省略stdio.h中,文件string.h和unistd.h中的夹杂物(上色隐藏标题包含code)。
All works fine but the C implementation is not working (there are no check-error code). The inclusion of stdio.h, string.h and unistd.h is omitted (the colorization hides the header inclusion code).
#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;
}
一些想法?
时的一个民意调查是个好主意实现它()代替presented解决方案?
Is a good idea implement it with a poll() instead the presented solution?.
先谢谢了。
推荐答案
修改:
好像 inotify的是用的东西。自2.6.13应该包含在Linux内核。 从IBM developerWorks上有关inotify的<一篇文章/ A>
EDIT: Seems like inotify is the thing to use. It should be included in linux kernel since 2.6.13 . An article from IBM developerworks about inotify.
previous答案:
Previous answer:
看一看Linux的文件变更监视器(在Linux内核2.4。 X>)。这是一个框架,它可以让你订阅文件更改,你从内核得到回调时发生变更。这应该是比轮询更好。
Have a look at Linux File Alteration Monitor (in linux kernels 2.4.x >). It's a framework that let's you subscribe for file changes and you get callback from kernel when change happens. This should be better than polling.
<一个href=\"http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=bks&fname=/SGI%5FDeveloper/books/IIDsktp%5FIG/sgi%5Fhtml/ch08.html\"相对=nofollow>范例如何轮询文件更改,检查出部分的等待文件的修改和轮询文件更改
Examples how to poll for file changes, check out sections Waiting for file changes and Polling for file changes.
我还没有尝试过呢。
这篇关于定制实施&QUOT;尾-f&QUOT;在C功能的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!