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

  • Is it possible to use lseek(fd,0) and then read(fd,buf) for the /proc/stat file instead of opening it again so that the next time I get the updated contents of this file?
  • And what causes the mmap() call after opening this file (see below)?

The problem I am facing is that the top reports are too low for CPU usage (10% versus 100% for software interrupts). Sagittarius indicates that the vertex does not reopen this file, but instead looks at the beginning and reads it again. And somehow, the content that is read from this file the next time does not match what I get when I run cat only for the /proc/stat file.

In addition, if I run top and cat /proc/stat in a loop at the same time, then top starts reporting the correct CPU usage.

Another difference is that top uses the mmap() call immediately after opening the /proc/stat file, and cat does not. I'm not sure if this could also be due to 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 image of 2.6.32-27 server. Intel Q6600 processor.

+8
linux cpu-usage procfs seek
source share
1 answer

It is very interesting what you ask ... I am starting to check my machine, but I do not see the difference between cat / proc / stat and execute top. Anyway, I'm at work, and I'm not quite โ€œfreeโ€ to do the tests.

The way you describe the "update" of an open file to read new data is correct ... if [f | l] seek () to the end, and then at the beginning of the file EOF will be updated and new data will be read.

I donโ€™t think that calling mmap () will cause the problem you mentioned, it can make reading faster, but nothing more (I'm not 100% sure).

I suggest you create a small C application that will open / proc / stat, read it, ask it and read it again to see how it updates, and also, if you need to do a stress test, it can be useful.

Now, answering your real questions:

  • Yes, AFAIK is sure, because you will โ€œwaitโ€ for new data in the file, and this should be better than opening and closing the file all the time.

  • It maps the file to the address space of the process, here are some information and examples:

http://www.gnu.org/s/libc/manual/html_node/Memory_002dmapped-I_002fO.html http://www.linuxquestions.org/questions/programming-9/mmap-tutorial-cc-511265/

+4
source share

All Articles