Open / close strategy for the / proc pseudo-profile

I wrote a C utility for Linux that checks the contents of / proc / net / dev once per second. I open the file using fopen ("/ proc / net / dev", "r") and then fclose () when I am done.

Since I use "pseudo" and not real, it matters whether I open / close the file every time I read it, or just open it when my application starts and keeps it open all the time? The utility starts as a daemon process and therefore can work for a long time.

+5
source share
2 answers

It doesn’t matter, no. However, there may be problems with caching / buffering, which will mean that in fact it is best (safer) to do as you do, and reopen the file every time. Since you do this so rarely, there is no performance that you will not get without doing this, so I would recommend keeping your current solution.

+3
source

What you want is unbuffered reading. Assuming you can't just switch to read () calls, open the device, and then set the stream to unbuffered mode. This has the added benefit of not having to close the stream when you are done. Just rewind it and start reading again.

FILE *f = fopen("/proc/net/dev", "r");
setvbuf(f, NULL, _IONBF, 0);
while (running)
{
    rewind(f);
    ...do your reading...
}
+2
source

All Articles