Skip to content
Advertisement

Discover “true” size of /proc/mounts

At the moment, I can determine when /proc/mounts changes using poll and the revents POLLERR | POLLPRI. I would now like to be able to compare the size of this pseudo-file before and after changing to determine whether a new mount has been attached, or an old one removed.

I have tried to use ioctl(fd, FIONREAD, &size), but it seems to report a nonsense size. I don’t want to have to buffer the entire output, because I would have to allocate quite a large buffer which wouldn’t be portable.

I am writing a C/C++ application which can listen and respond to mount-point changes. More specifically, when a USB mass-storage device is attached to the system, I want my program to be able to:

  1. Identify that a new partition has been mounted.
  2. Check the contents of that partition.
  3. If the partition contains a file with a particular name, do something with that file.

I believe that my current approach is unsuitable.

Advertisement

Answer

It is conceivable that the mounts have changed but /proc/mounts file size stays the same. The file size is not a robust summary of the file contents.

I don’t want to have to buffer the entire output, because I would have to allocate quite a large buffer which wouldn’t be portable.

Read the file character-by-character or line-by-line and make a hash of all characters (hash of the file contents). Compare the current hash with the previous one to determine whether the file contents have changed.


Your application can parse /proc/mounts or /proc/self/mountinfo, build a sorted list of mounts (e.g. mount-point and major-minor) and keep it. When /proc/mounts is updated, parse again and build a new sorted list, compare it with the kept one to determine mount additions/removals, act on the additions/removals, replace the kept list with the new one.

Advertisement