Created
September 15, 2013 10:36
-
-
Save kotnik/6569574 to your computer and use it in GitHub Desktop.
Proper way to consistently read `/proc/mounts`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import collections | |
def get_current_mounts(): | |
""" Get the currently mounted filesystems. """ | |
# Reading from /proc/mounts is only consistent within a single read(3) | |
# call. Unfortunately, the maximum amount of data you can get from | |
# this file in a single call is hardcoded by the kernel to PAGE_SIZE | |
# (4096 bytes on x86). As a consequence, there is no way to read | |
# from this file in a consistent manner. | |
# | |
# As a (arguably ugly) workaround, we read from /proc/mounts until we | |
# get two reads in a row that are consistent with each other. | |
# | |
previous_data = None | |
data = None | |
while True: | |
with open("/proc/mounts", "rb") as f: | |
data = f.read() | |
if data == previous_data: | |
break | |
else: | |
previous_data = data | |
mounts = collections.OrderedDict() | |
for line in data.split("\n"): | |
line = line.strip() | |
if len(line) == 0: | |
continue | |
info = {} | |
cols = re.split("\s+", line) | |
info["source"] = cols[0].rstrip("/") | |
info["mount-point"] = cols[1] | |
info["fs-type"] = cols[2] | |
info["options"] = cols[3] | |
info["dump"] = cols[4] | |
info["pass"] = cols[5] | |
mounts[info["mount-point"]] = info | |
return mounts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment