I have a python script (ran as root) that needs to be able to mount and unmount the filesystem of a USB flashdrive. Ive did some research and i found this answer https://stackoverflow.com/a/29156997 which uses ctypes. However. the answer only specifies how to mount, so ive tried to create a similar function to unmount the device. So all in all i have this:
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, trying the unmount command with option "0" or "1" like:
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 it with 2 as the option:
unmount('/dev/sdb', 2)
unmounts ALL my filesystems, including '/', resulting in a system crash.
All of this still applies even if i replace the device number with the specific partition:
/dev/sdb -> /dev/sdb1
What am i doing wrong?