Question

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;
}
Was it helpful?

Solution

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).

OTHER TIPS

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

once you complete read operation,close your file there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top