3

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?

  • Are you sure sdb isn't your hard drive? List your devices with flash drive plugged in and removed and compare the list. – Harrichael Jul 26 '17 at 20:54
  • Im very sure. Since this script will eventually format and partition said drive ive taken extra precautions to ensure that this is the right device –  Jul 26 '17 at 20:58
  • Have you mounted and unmounted successfully with system commands then? – Harrichael Jul 26 '17 at 21:02
  • Yes i did. I tried both mount and unmount. its also important to note that trying unmount from my script with option 3 resulted in a system crash as well –  Jul 26 '17 at 21:12
  • I recommend using subprocess calls to narrow down your list of problems. – Harrichael Jul 26 '17 at 21:13
  • Subprocess works like a charm but i have to specify the specific partition to unmount –  Jul 26 '17 at 21:29

0 Answers0