Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refresh stream buffer while reading /proc

Tags:

c

linux

I'm reading from /proc/pid/task/stat to keep track of cpu usage in a thread. fopen on /proc/pic/task/stat fget a string from the stream sscanf on the string

I am having issues however getting the streams buffer to update. If I fget 1024 characters if regreshes but if I fget 128 characters then it never updates and I always get the same stats. I rewind the stream before the read and have tried fsync.

I do this very frequently so I'd rather not reopen to file each time. What is the right way to do this?

like image 328
Brian Makin Avatar asked Oct 14 '22 17:10

Brian Makin


1 Answers

Not every program benefits from the use of buffered I/O.

In your case, I think I would just use read(2)1. This way, you:

  • eliminate all stale buffer2 issues
  • probably run faster via the elimination of double buffering
  • probably use less memory
  • definitely simplify the implementation

For a case like you describe, the efficiency gain may not matter on today's remarkably powerful CPUs. But I will point out that programs like cp(2) and other heavy-duty data movers don't use buffered I/O packages.


1. That is, open(2), read(2), lseek(2), and close(2).
2. And perhaps to intercept an argument, on questions related to this one someone usually offers a "helpful" suggestion along the lines of fflush(stdin), and then another someone comes along to accurately point out that fflush() is defined by C99 on output streams only, and that it's usually unwise to depend on implementation-specific behavior.

like image 132
DigitalRoss Avatar answered Nov 08 '22 02:11

DigitalRoss