1

我正在实现一个轻量级应用程序,我必须经常打开并阅读 /proc/pid 或 tid/task/stat 详细信息。如果应用程序是多线程的,我必须阅读更多的统计文件。所以打开,阅读和关闭让我的监控应用程序真的很慢。是否有避免重复打开文件并仍然能够读取更新内容的解决方案?

我进行了以下实验,但没有看到成功。我更改了“test.txt”中的数据,但未读取新数据。是因为文件没有在内存中更新吗?当我修改并保存“test.txt”时会发生什么?

#include <stdio.h>
int main()
{
    FILE * pFile;
    char mystring [100];
    pFile = fopen ("test.txt" , "r");
    while(1){
        if (pFile == NULL) perror ("Error opening file");
        if ( fgets (mystring , 100 , pFile) != NULL ){
            puts (mystring);
            fseek ( pFile , 0 , SEEK_SET );
        }
        sleep(1);
    }
    fclose (pFile);
    return 0;
}
4

2 回答 2

1

尝试这样的事情:

for (;;) {
    while ((ch = getc(fp)) != EOF)  {
        if (putchar(ch) == EOF)
            perror("Output error");
    }
    if (ferror(fp)) {
        printf("Input error: %s", errno);
        return;
    }
    (void)fflush(stdout);
    sleep(1); // Or use select
}

您可以通过研究tail 的源代码找到完整的示例。上面的代码是对 forward.c 的修改摘录。

您可以使用select来监视多个文件的新数据(您需要保持它们打开)。

于 2013-10-23T10:51:26.290 回答
0

Give a try with rewind() and don't close your file.

once you complete read operation,close your file there.

于 2013-10-23T10:36:14.180 回答