Skip to content

Instantly share code, notes, and snippets.

@abg
Created May 9, 2014 18:26
Show Gist options
  • Save abg/bdc7dff08b64820a30b1 to your computer and use it in GitHub Desktop.
Save abg/bdc7dff08b64820a30b1 to your computer and use it in GitHub Desktop.
python api to create process private mountpoints; essentially just a wrapper to unshare(2)
import ctypes
import ctypes.util
import errno
# <sched.h> constants for unshare
CLONE_NEWNS = 0x00020000
# <sys/mount.h> - constants for mount
MS_REC = 16384
MS_PRIVATE = 1 << 18
MS_SLAVE = 1 << 19
_libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
try:
_unshare = _libc.unshare
except AttributeError:
_unshare = None
else:
_unshare.argtypes = [ ctypes.c_int ]
_unshare.restype = ctypes.c_int
try:
_mount = _libc.mount
except AttributeError:
_mount = None
else:
# int mount(const char *source, const char *target,
# const char *filesystemtype, unsigned long mountflags,
# const void *data);
_mount.argtypes = [
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.c_ulong,
ctypes.c_void_p
]
_mount.restype = ctypes.c_int
try:
_umount = _libc.umount
except AttributeError:
_umount = None
else:
# int umount(const char *target);
_umount.argtypes = [ctypes.c_char]
_umount.restype = ctypes.c_int
def unshare():
if _unshare is None or _mount is None:
raise OSError(errno.EINVAL, "unshare is not supported on this platform")
if _unshare(CLONE_NEWNS) != 0:
_errno = ctypes.get_errno()
raise OSError(_errno, errno.errorcode[_errno])
# mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)
if _mount(None, "/", None, MS_SLAVE|MS_REC, None) != 0:
_errno = ctypes.get_errno()
raise OSError(_errno, errno.errorcode[_errno])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment