2

I am implementing a low weight application where I have to open and read the /proc/pid or tid/task/stat details very often. If the application is multithreaded I have to read more stat files. So opening, reading and closing makes my monitoring application really slow. Is there a solution to avoid opening the file repeatedly and still able to read the updated content?

I ran the following experiment but I don't see success. I change the data in "test.txt" but the new data is not read. Is it because the file is not updated in memory? What happens when i modify and save "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;
}
dragosht
  • 3,237
  • 2
  • 23
  • 32

2 Answers2

2

Try something like this:

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
}

You can find a full example by studying the source code for tail. The code above is a modified excerpt from forward.c.

You can use select to monitor several files for new data (you need to keep them open).

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • @Surya If you get an answer that solves your problem you should accept that answer. Accepting answers will make other people more prone to answer your question. If you find answers helpful you can also upvote them (only one answer can be accepted, but any number, up to a limit of 40 per day, can be upvoted). – Klas Lindbäck Oct 24 '13 at 12:08
  • That solution works to read refreshed file but as its 2 infinite loops it can and cannot be used in all applications which has time bounds. – Surya Narayanan Oct 25 '13 at 12:48
1

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

once you complete read operation,close your file there.

Shiva
  • 531
  • 4
  • 6
  • 14