The correct way to read / proc / pid / status

I read /proc/<pid>/status as follows:

 std::ifstream file(filename); std::string line; int numberOfLinesToRead = 4; int linesRead = 0; while (std::getline(file, line)) { // do stuff if (numberOfLinesToRead == ++linesRead) { break; } } 

I noticed that in rare cases std::getline hangs.

  • Why is this happening? I got the impression that the proc file system should be in a somewhat consistent state and there should be no cases where a new line is missing. My assumption was that getline returns false when an EOF / error occurs.
  • What is the recommended, safe way to read /proc/<pid>/status ?
+5
source share
2 answers

Perhaps a better way is to use fread in a large buffer. The status file is small, so allocate a local buffer and read the entire file.

Example consider the second answer for the simplest solution.

This may still not work on fopen or fread, but a reasonable error should be returned.

0
source

/ proc is a virtual file system . This means that reading from "files" in it does not match reading from a regular file system.

If the process terminates, information about this is deleted from / proc much faster than if it were a real file system (the dirty cache reset delay was involved here).

Given this, imagine that the process ends before you read the next line, which has not yet been buffered.

The solution is to take into account the loss of the file, as you may not need information about a process that no longer exists, or buffer the entire file and then analyze it.

EDIT: The hang in the process should be explicitly related to the fact that it is a virtual file system. It does not behave exactly like a real file system. Since this is a specific type of fs, the problem may be in the fs driver. The code you provide is great for reading files normally.

-2
source

All Articles