How to mount and unmount Linux filesystems using ctypes, mount and umount
I have a python script (running as root) that should be able to mount and unmount a USB flashdrive filesystem. Ive done some research and I found this answer on StackOverflow question which uses ctypes. However. the answer specifies how to mount, so I tried to create a similar function to unmount the device. So, I have it all:
import os
import ctypes
def mount(source, target, fs, options=''):
ret = ctypes.CDLL('libc.so.6', use_errno=True).mount(source, target, fs, 0, options)
if ret < 0:
errno = ctypes.get_errno()
raise RuntimeError("Error mounting {} ({}) on {} with options '{}': {}".
format(source, fs, target, options, os.strerror(errno)))
def unmount(device, options=0):
ret = ctypes.CDLL('libc.so.6', use_errno=True).umount2(device, options)
if ret < 0:
errno = ctypes.get_errno()
raise RuntimeError("Error umounting {} with options '{}': {}".format(device, options, os.strerror(errno)))
However, try unmount command with parameter "0" or "1", for example:
unmount('/dev/sdb', 0)
or
unmount('/dev/sdb', 1)
gives the following error:
Traceback (most recent call last):
File "./BuildAndInstallXSystem.py", line 265, in <module>
prepare_root_device()
File "./BuildAndInstallXSystem.py", line 159, in prepare_root_device
unmount('/dev/sdb', 0)
File "./BuildAndInstallXSystem.py", line 137, in unmount
raise RuntimeError("Error umounting {} with options '{}': {}".format(device, options, os.strerror(errno)))
RuntimeError: Error umounting /dev/sdb with options '0': Device or resource busy
while running with 2 as an option:
unmount('/dev/sdb', 2)
shuts down ALL of my filesystems, including "/", causing the system to crash.
All of this still applies even if I replace the device number with a specific partition:
/dev/sdb -> /dev/sdb1
What am I doing wrong?
+3
user8372417
source
to share
No one has answered this question yet
See similar questions:
or similar: