3

我有一个 python 脚本(以 root 身份运行),它需要能够挂载和卸载 USB 闪存驱动器的文件系统。我做了一些研究,我发现了这个答案https://stackoverflow.com/a/29156997它使用 ctypes。然而。答案只指定了如何挂载,所以我尝试创建一个类似的函数来卸载设备。所以总而言之,我有这个:

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)))

但是,尝试使用选项“0”或“1”的卸载命令,例如:

unmount('/dev/sdb', 0)

或者

unmount('/dev/sdb', 1)

给出以下错误:

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

使用 2 作为选项运行它时:

unmount('/dev/sdb', 2)

卸载我的所有文件系统,包括“/”,导致系统崩溃。

即使我用特定分区替换设备号,所有这些仍然适用:

/dev/sdb -> /dev/sdb1

我究竟做错了什么?

4

0 回答 0