Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open/close strategy for /proc pseudo-file

Tags:

c

linux

file-io

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

Since I'm using a 'pseudo' file rather than a real one, does it matter if I open/close the file each time I read from it, or should I just open it when my app starts and keep it open the whole time? The utility is launched as a daemon process and so may run for a long time.

like image 668
codebox Avatar asked Oct 26 '09 08:10

codebox


2 Answers

It shouldn't matter, no. However, there might be issues with caching/buffering, which would mean it's actually best (safest) to do as you do it, and re-open the file every time. Since you do it so seldom, there's no performance to be gained by not doing it, so I would recommend keeping your current solution.

like image 86
unwind Avatar answered Nov 18 '22 13:11

unwind


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 additional advantage that there is no need to close the stream when you're 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...
}
like image 2
Matt Joiner Avatar answered Nov 18 '22 15:11

Matt Joiner