Is it safe to use lseek() when reading from Proc-FS files second time


  1. Is it safe to use lseek(fd,0) and then read(fd,buf) for /proc/stat file instead of reopening it to get updated contents of this file next time?
  2. And what does the mmap() call after opening this file really do (see below)?

The problem I am encountering is that top reports way too low CPU usage (10% vs 100% for software interrupts). The strace tool indicates that top does not reopen this file but instead lseeks to beginning and reads it once again. And somehow the contents which are read from this file next time does not match with what I would get when I run cat for /proc/stat file alone.

Also If I run top and cat /proc/stat in a loop at the same time then top starts to report correct CPU-Usage.

One more difference I spot is that top uses mmap() call right after opening the /proc/stat file, while cat does not do that. I am not sure if this also could be related with my problem (because filesdes=-1 here):

mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f7b37649000

I am using Ubuntu 10.04.1 Desktop edition with 2.6.32-27-server image. The CPU is Intel Q6600.


It’s very interesting what you ask… I start checking in my machine but I don’t see differences between cat /proc/stat and execute top. Anyway, I’m at work and I’m not totally ‘free’ to make tests.

The way you describe to ‘refresh’ the opened file to read new data is correct… in case of a [f|l]seek() call to the end and then to the beginning of the file will update the EOF and new data will be read.

I don’t think that the mmap() call will cause the problem you mentioned, it could make the read faster, but nothing else (I’m not 100% sure).

I would suggest you to make a small app in C that open /proc/stat, read it, seek it and read it again to see how it’s updated, also if you have some stress test to do could be useful.

Now, answering your real questions:

  1. Yes, AFAIK it’s sure because you will be ‘waiting’ for new data on the file and it should be better than open and close the file all the time.

  2. It maps a file to the process address space, here are some info and examples:

Answered By – webbi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published