When it comes to installing openSUSE or to adding/removing disks to an existing system, people start talking about mounting and umounting, and about filesystems and partitions. Some people have little real idea of what all these words mean in a Unix/Linux environment which means that discussing problems in this area is full of potential misunderstandings.
Many people do have some knowledge based on familiarity with other Operating Systems. That increases the possibility of confusion.
This page aims at clarifying this vocabulary considered in a Unix/Linux environment.
- Notion of Disk
- Notion of partition
- Disk Partitioning in a PC
- Legacy Partitioning and Booting
- The Basic Principles
- Primary, Extended and Logical Partitions
- GPT Partitioning and Booting with a UEFI Firmware
- The Linux Filesystem and its Setting Up
- Description of the Linux Filesystem
- Files in Linux
- Structure of the Filesystem
- Devices Files and Special Files — Naming of disks and Partitions
- Preparing the Partition Before Installation
- Setting Up the Filesystem — Mounting and Unmounting of Partitions
- Initialization in RAM
- Notion of Mounting and Unmounting
- Determination of Partition to Be Mounted
- Mounting Partitions after Installation
- Standard Organization of the Filesystem
- Prerequisites
- Linux file system
- How to use mount Command in Linux
- Mount a Linux filesystem
- Mount a device
- /etc/fstab File
- Remounting All File Systems
- List Mount Point
- Conclusion
- Overview
- Mount Points
- Root Filesystems
- Pivot root
- Implementation
- PID Namespaces
- Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
- Re: Вопрос по Mount Point’ам в Линуксе
Notion of Disk
In this document, the word disk will be used as a generic term for anything that is seen by operating systems as a disk drive i.e. a place where they can store and retrieve data perennially — perennially implying the idea of nonvolatility when powering the computer off. No matter whether it is a flash device that looks like a disk, an optical drive or a ‘real’ hard disk, or even a combination of several devices.
Because newer types of mass storage devices present themselves to the system as disks, they fall into this category. The operating systems can not see if a disk is inside the system enclosure, beside it, on a table, or on another shelf, so there is no difference between what some people call internal and external disks.
Disks are normally supplied formatted by the manufacturer. That means that damaged tracks are marked and replacements used, sector numbers are written. This is done to interface with the controller’s hardware and firmware. This type of formatting is also known as low-level formatting.
Notion of partition
It is often necessary — especially when one wants to install several operating systems on the same computer — to divide the hard disk into several regions and to attribute every one of them to such or such operating system. This dividing is done by an operation called partitioning and the created regions are called partitions. Each system can store and retrieve data on these partitions independently from other operating systems.
To access the partitions, the operating systems have to read a very particular area of the disk, called the Partition Table. The partition table contains information about the size and the location of the partitions.
To be usable by an OS, a disk must include at least one partition but generally there are more. An OS can use several partitions even if they belong to different disks.
The different partitions of disks on a machine are seen, regardless of their physical nature, as mass storage volumes. This is why they are referred to as volumes. One of these partitions is marked in a specific way as the boot partition. This marking is called Boot Flag.
- In Windows, partitions are named after a letter followed by a colon e.g. , , etc. The Windows system itself is always located in .
- In Linux, partitions are named after the path from the unique root of the tree — into which all directories and files (including device files) are placed to constitute the entire filesystem — to their location in this tree. Generally they are named /dev/hd<a letter>/<a number> or /dev/sd<a letter>/<a number> e.g. or . We will bring more light upon this at the time of speaking of the filesystem in Linux.
Disk Partitioning in a PC
Legacy Partitioning and Booting
The Basic Principles
At the beginning, when disks had little space, there was the idea that four partitions would be enough for all possible usage (but this proved false). With this kind of partitioning, data about partitions — number, location, size, type, etc. — is written in the partition table which is located in a particular sector at the very beginning of the disk and in which the firmware — called Basic Input Output System (BIOS) — fetches the instructions in order to boot the machine. This boot sector is known as the Master Boot Record (MBR) and includes the code necessary to the continuation of the loading of the OS.
The boot program included in the MBR alongside the partition table is sometime called the boot loader. It works often as the first stage of a loading mechanism handing the control to a second stage located in a particular sector of an other partition: the Volume Boot Record (VBR).
The boot manager may be placed, depending on the case, either directly into the MBR of the boot disk or into the VBR of a partition — the one which boot flag is set to indicate that it is the boot partition. Among the most well known boot manager, are GRUB and Lilo.
Primary, Extended and Logical Partitions
When it became very obvious that four partitions were not going to be sufficient, a backwards-compatible solution was found: make one of the four partitions — which were then called primary partitions — a special partition called the extended partition that can hold more partitions — the logical partitions.
Newer BIOSes (nowadays all BIOSes) know about it. Thus we have 3 types of partitions:
- primary partitions, these are the partitions of old, there can be four of them (numbered 1, 2, 3, 4);
- extended partition (in fact also a primary partition) — there can only be one, it has normally the number after the highest created primary partition (3 or 4) and should contain all of the remaining space of the disk (otherwise space is wasted);
- logical partitions — they are created inside the extended partition, their numbers are always 5 and higher (the maximum is debatable, but enough for most people).
Some people are bewildered by the extended partition, it seems to be of no use and takes a lot of disk space and that space seems also to belong to other useful partitions; of course, the extended partition is acting as a container for the secondary partitions, and so space shows up in both the extended partition and the secondary partitions that it contains. Reading the above might reassure them.
An example of a disk with partitions of all three types goes here:
fdisk -l
Disk /dev/sda: 200.0 GB, 200049647616 bytes 255 heads, 63 sectors/track, 24321 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disklabel type: dos Disk identifier: 0x1c841c84 Device Boot Start End Blocks Id System /dev/sda1 1 574 4604008+ c W95 FAT32 (LBA) Partition 1 does not end on cylinder boundary. /dev/sda2 * 575 8967 67416772+ 7 HPFS/NTFS /dev/sda3 8968 24321 123331005 f W95 Ext'd (LBA) /dev/sda5 8968 9229 2104483+ 82 Linux swap / Solaris /dev/sda6 9230 11840 20972826 83 Linux /dev/sda7 11841 24321 100253601 83 Linux
- Partition 1 is a restore partition put there by the PC’s manufacturer.
- Partition 2 contains a Windows XP system (Windows calls it the drive).
- Partition 3 is the extended partition, which runs until the end of the disk and holds the following three:
- Partition 5 is the openSUSE partition.
- Partition 6 is the openSUSE partition.
- Partition 7 is the openSUSE partition.
- The Disklabel type line indicates that it is a dos partition table.
- The star in front of indicates location of the boot flag, identifying the partition where Windows-compatible MBR code jumps to continue the boot process. There must be a boot flag on one primary partition, unless other than Windows-compatible MBR code is used, such as that used by LILO and Grub.
- GPT stands for GUID Partition Table.
- GUID stands for Globally Unique Identifier.
- UEFI stands for Unified Extensible Firmware Interface. UEFI is the standard that defines the software which constitutes the interface between the firmware — itself in direct connection with the hardware — and the operating system. UEFI has supplanted the good old BIOS. To discover more about UEFI please read the page dedicated to UEFI.
Although the GPT partitioning is closely associated with UEFI, it is not inconsistent with computers provided with a BIOS. The BIOS is in fact unaware of the type of partition that is indicated on the disk because it is not its role to interpret the partition table. This task is delegated to the boot loader and software that will take hold of the computer after it. The BIOS requires the MBR only to find in it the first stage boot loader code and it is the GPT partitioning that provided the MBR for him, in the form of the Protective MBR. This protective MBR describes one 0xEE type of partition that covers the entire GPT drive. However, if the disk size exceeds 2TB, the protective MBR describes the disk as containing only one partition of 2TB and nothing else. Software that does not recognize the GPT sees the disk as a completely full disk with a partition of a kind it does not know and can not change the disk without erasing this partition, which limits the risk of accidental erasure.
GPT Partitioning and Booting with a UEFI Firmware
The Linux Filesystem and its Setting Up
Description of the Linux Filesystem
Files in Linux
It is customary to say that in Linux «almost everything is a file; if something is not a file, it is a process.» However, Linux distinguishes between different categories of files:
- Regular files that contain data such as e.g. text, program instructions, pictures, video recording, etc.
- Directories that are really just files containing a list of files.
- Special files that represent the mechanism used for input and outputs and that are placed in the directory.
- Sockets, special files for inter-process communication through the network.
- Links a mechanism to make a visible file in multiple locations of the file system.
- Pipes which allows inter-process communication with a lean semantics relatively to the sockets.
We will come back to some of these concepts later in this page.
Structure of the Filesystem
In Linux, all files and folders are placed in a single root tree. This root is called root and is spotted by the sign in Linux commands. The volumes used to contain these files (or folders) do not obviously appear in the tree that makes them completely abstracted. Each of the used volumes includes part of the tree but is not very visible.
Note here already some notable differences compared to Windows systems where:
- the files are placed in one of the many trees whose roots are each of the volumes such as , , etc.
- the separator of tree levels is instead of .
Devices Files and Special Files — Naming of disks and Partitions
At boot time, the Linux system scans the hardware and associates to each of the discovered devices a special file a.k.a. device file. This special file — name given because it has no content on the disc, but it is used as a file — is a kind of interface between the device driver and hardware. The driver just writes to this device-file for output and reads in it to make an entry. These device-files are usually placed in the directory.
Disks are generally associated with the special-files (device files) for PATA units for SATA drives. The partition of these disks are indicated by or and placed in the directory e.g. /dev/hda, /dev/hda1, /dev/hda2, /dev/sda, /dev/sda1, /dev/sda2, /dev/sdb, etc.
Preparing the Partition Before Installation
Beyond the low level formatting and the making of the partitions, there is still left one operation without which operating systems are unable to make use of the partitions: the high level partitioning. In fact, this operation aims at putting a branch of the filesystem. This branch is completely void but ready to receive directories and files and to prepare the VBR — the famous VBR we spoke of previously. In Linux, as if it wanted to insist on what this formatting does, calls it mkfs. — mkfs being a contraction of make filesystem. It is the reason why, in the literature, we will find the wording make a filesystem instead of format.
mkfs.ext4 /dev/sdc1
Normally, during the installation of openSUSE , you do not have to do it by hand , you simply declare the desired type in the GUI and the YaST installer does it for you .
Setting Up the Filesystem — Mounting and Unmounting of Partitions
Initialization in RAM
When starting the system, after the kernel has been loaded into memory by the boot loader , a minimum file system is created in memory from an image stored using various techniques, the explanation of which goes far beyond the limits fixed to this page. This filesystem is virtual, in the sense that it resides in volatile memory . It will become little by little real in the sense of living on non-volatile media , by means of mounting operations to be described now . This is because , this virtual initial system contains all the necessary drivers to mount different partitions — with their filesystem — that the thing is made possible.
Notion of Mounting and Unmounting
Mounting and Unmounting Illustration
Of course, if the partition is then unmounted, the hidden directory is discovered anew while the directories of the partition are made unreachable anew.
To finish, the unmounting of partition restore the initial state.
It must be noted that for a mounting operation to succeed, it is necessary that the mounting point exists in the filesystem tree. The mounting order is also important. To ignore this can lead to the impossibility to mount a partition or to the hiding of a mounting by a mounting that should have been done prior to it.
Determination of Partition to Be Mounted
- a swap partition that will be used as an extension of the computer’s RAM;
- a partition to be mounted on the filesystem’s root;
- a partition to be mounted on the mount point, the use of which will be for users directories and files in order to keep them clearly segregated from the Linux system.
Had the reader been sufficiently attentive, he should have asked himself: «How can the system use this file if it resides on a partition that is not yet mounted?» The answer is that, at boot time, the kernel is notified the root=/dev/sd information based on which it can tentatively and read-only mount the partition that contains the final filesystem and find in it the file to determine which other partitions to mount.
Mounting Partitions after Installation
Case of Removable Media
To do so, he can use the graphical file explorer of the desktop environment or use the umount command:
umount <path to partitions mount point>
Case of Irremovable Media
One can discover after the installation of openSUSE in dual boot with Windows that he needs to access numerous files inside the Windows partition and that unfortunately this partition has not been declared to be mounted by the system.
- If the need is temporary, it is possible to use a tool such as Gnome-disk-utility to make a temporary mounting on .
The mounted partition then appears in the file explorer. It is also accessible from the command line — please refer to the basic commands of Linux.
- If the need is permanent, one can add a line to the file. At the next booting, the new line will be taken into account and the partition mounted as required by the options defined in
Standard Organization of the Filesystem
All files in Linux are present as a node of a tree rooted at /. Initially, the parent directory (ext4 in default mode with Linux) is mounted to this root directory and all files added by Linux during installation are saved under this parent directory.
Any removal/non-removal storage devices can then be mounted to the root node. For example, whenever external USB flash drives are mounted to the root it becomes discoverable by the Linux file system, and files on the drive can then be accessed as it becomes part of the root.
The Linux mount command works to facilitate the attachment of the device’s file system to the root of the tree. A mount point in Linux is the directory where the mounted file system gets attached.
In this tutorial, we learn about mount command in Linux.
Prerequisites
- A terminal to run commands.
- Requires root or sudo privileges to mount drives and filesystems.
- Good understanding of Linux filesystem.
Linux file system
Filesystem on Linux defines the systematic storage of data on the disk. It defines how and what data will be stored while saving a file including where the data will be stored and how the data will be retrieved from the disk. A few examples of Linux file systems include ext, ext4, XFS, swap, and ReiserFS.
Filesystems are responsible for defining how the inodes will store the data. This characterization forms the base construct for the maximum size of file which the filesystems support and the maximum size of volumes that the filesystem can mount with.
The mount command is used to attach a filesystem on an external device to the root node (/) of the tree (Linux file system) using the terminal. The entire file hierarchy in Linux filesystems is mounted to this root. We can use umount command to detach the device from the root.
The standard syntax for linux mount command is:
mount -t type device dir
This communicates to the kernel to detect and attach the file system present on the device to the directory dir.
If only the directory or the device is given as input then the mount command looks for the mount point in the file /etc/fstab. For example, mount /dir
mount command has the option to specify the source and target device paths which helps in avoiding ambiguity while mounting the device to a target location.
mount --source <source> --target <target>
There are multiple options that mount command support to help with additional flexibility while mounting.
How to use mount Command in Linux
Mount command instructs the operating system that the files on external devices are ready to be associated at a specified mount point in the Linux tree hierarchy rooted at /.
Mount a Linux filesystem
Mounting filesystems of a device in Linux filesystem consists of 2 steps — creating the mount point and mounting the device.
Let’s take an example of mounting ISO image:
Create a mount point:
mkdir /media/iso
Mount the ISO file in the Linux file system:
mount -o loop /source/path_to_iso_image.iso /media/iso
Mount a device
mount command provides the liberty to attach external storage devices through the command line. For example, you can mount or unmount a USB flash drive, CD-ROM, hard disk device, etc.
Each of these external storage devices gets mounted as a node in the Linux file system tree which is rooted at /.
Once mounted, the files on these external devices are made accessible for read/write on the Linux system as the Linux filesystem can now read through the file paths and interrupt the data stored on the file.
One of the necessary command while mounting a device in Linux is fdisk
fdisk -l
fdisk is used to manipulate the partition table of the disk. When the parameter -l is passed in, it lists all the partition tables for the device specified in the arguments.
If there are no devices passed in as arguments for this command it gets the devices mentioned in /proc/partitions
Let’s take an example to understand how to mount an external usb flash drive:

Check for USB drive based on the filesystem and the device size. In the above example, it’s /dev/sdb1 with GPT filesystem.
Instead of using /dev/sda2, you may also use by uuid, id or path.ls -l /dev/disk/by-uuid/ 11169433-051f-4b3b-bd05-7c31c85f0d47 -> ../../sda2
ls -l /dev/disk/by-id/ ata-Samsung_SSD_870_QVO_1TB_S5SVNG0N955653H-part2 -> ../../sda2
ls -l /dev/disk/by-path/ pci-0000:02:00.1-ata-1-part2 -> ../../sda2
Step 2: Create a mount point for the usb drive.
This can be any existing or new directory within the Linux filesystem. We are using mkdir to create the new mount point where we want the usb flash drive to mount.
sudo mkdir /media/usb-dsk
Step 3: Mount the usb partition /dev/sdb1 to the mount point created in step 2.
sudo mount /dev/sdb1 /media/usb-dsk

Step 4: Run mount command to ensure that the mount was successful.
sudo mount | grep sdb1
/etc/fstab File
fstab file contains information about different file systems that the Linux system can mount. It stores the data in a tabular format where each column specifies the rules to control different file systems while mounting/unmounting them.
The order of the entries in the table are important as the filesystems on top of the list are mounded first. Each line represents a new filesystem for mounting.
The content of this file is read by the mount command for mounting different available filesystems. The command is executed automatically at boot where again mount reads the fstab file to get the list of available filesystems for mount.
The table in the file comprises of 6 columns specifying:
- device — name or the UUID of the currently mounted filesystems
- mount-point — path to the directory where the device is currently mounted
- fs-type — the filesystem type of the device, eg, ext4, swap, etc.
- options — describes the mount options available with the filesystem
- dump — used by dump to understand if the file system needs to dumped
- pass — defines the order in which the file systems check needs to be done at boot time by fsck
/proc/mounts file stores the default system mount options for the Linux file systems and it’s used by Kernel to display the statuses of all currently mounted file systems with Linux.
Remounting All File Systems
The filesystems are mounted in the order of their presence in fstab.
The command once executed compares the source and target for file systems which are already mounted and the kernel tables with already mounted filesystems are cached.
mount -a
Remounts all the filesystems in fstab. In other words, it attempts to remount the already mounted filesystem.
List Mount Point
mount command in Linux provides the flexibility to check the mounted devices in the Linux filesystem.
Often these are useful when you want to confirm and diagnose if the devices or the directory or the file on the device is mounted to the Linux filesystem.
Additionally, Linux also provides alternative commands to get the list of all mounted file systems which are discussed below.
There are different methods to get the mounted devices on Linux:
- mount
When the mount command is executed without any arguments, it returns the list of currently mounted file systems.
- mount -l
The option -l displays all the mounted filesystems along with their corresponding labels.
df stands for disk filesystem and it is often used to get the space available on all the mounted filesystems with each file name argument.
If there are no file name passed as argument, then the command returns the space available on all the mounted filesystems.
- mount -t ext4
This command returns all the mount filesystems of type ext4. The supported file systems types depend on the underlying kernel.
We can list more than 1 filesystem type as a comma-separated list of parameters.
- lsmod
Returns the status of modules loaded in the Linux file system along with the size of these modules in bytes and the number of times they are being used by the running programs.
The command returns currently loaded kernel modules by reading and formatting content of the file /proc/modules
Conclusion
We discussed the different command line options that can help to find mount points. Towards the end of this tutorial we discussed how the different filesystem remains mounted and the different filesystem mount options available in the Linux filesystem.
Overview
Mount namespaces isolate filesystem resources.
This pretty much covers everything that has to do with files on the system.
Among the encapsulated resources is a file containing the list of mount points that are visible to a process and as we hinted at in the intro post, isolation can enforce that changing the list (or any other file) within some mount namespace instance M
does not affect that list in a different instance (so that only the processes in M
observe the changes).
Mount Points
You might be wondering why we just zoomed in on a seemingly random file that contains a list — what’s so special about it?
The list of mount points determines a process’ entire view of available filesystems on the system and since we’re in Linux land with the everything is a file mantra, the visibility of pretty much every resource is dictated by this view — from actual files and devices to information about which other processes are also running in the system.
So it’s a huge security win for isolate
to be able to dictate exactly what parts of the system we want commands that we run to be aware of. Mount namespaces combined with mount points are a very powerful tool that lets us acheive this.
We can see mount points visible to a process with id $pid
via the /proc/$pid/mounts
file — its contents is the same for all processes that belong to the same mount namespace as $pid
:
/proc//mounts
...
/dev/sda1 / ext4 rw,relatime,errorsremount-ro,dataordered 0 0
...
Spotted somewhere in the list returned on my system is the /dev/sda1
device mounted at /
(yours might differ). This is the disk device hosting the root filesystem that contains all the good stuff needed for the system to start and run properly so it would be great if isolate
runs commands without them knowing about filesystems like these.
Let’s start by running a terminal in its own mount namespace:
# The -m flag creates a new mount namespace.
unshare bash
/proc//mounts
...
/dev/sda1 / ext4 rw,relatime,errorsremount-ro,dataordered 0 0
...
The shell process is in fact running in a different mount namespace (we can verify this by comparing the symlinked file ls -l /proc/$$/ns/mnt
to that of another shell running in the root mount namespace).
The reason we still see the same list is that whenever we create a new mount namespace (child), a copy of the mount points of the mount namespace where the creation took place (parent) is used as the child’s list.
Now any changes we make to this file (e.g by mounting a filesystem) will be invisible to all other processes.
However, changing pretty much any other file at this point will affect other processes because we are still referencing the exact same files (Linux only makes copies of special files like the mount points list).
This means that we currently have minimal isolation. If we want to limit what our command process will see, we must update this list ourselves.
Now, on one extreme, since we’re trying to be security conscious, we could just say F* it and have isolate
clear the entire list before executing the command but that will render the command useless since every program at least has dependencies on resources like operating system files, which in turn, are backed by some filesystem.
On the other extreme, we could also just execute the command as is, sharing with it, the same filesystems that contain the necessary system files that it requires but this obviously defeats the purpose of this isolation thing that we have going on.
The sweet spot would provide the program with its very own copy of dependencies and system files that it requires to run, all sandboxed so that it can make any changes to them without affecting other programs on the system.
In the best case scenario, we would wrap these files in a filesystem and mount it as the root filesystem (at the root directory /
) before executing the un-suspecting program.
The idea is, because everything reachable by a process must go via the root filesystem and because we will know exactly what files we put in there for the command process, we will rest easy knowing that it is properly isolated from the rest of the system.
- Create a copy of the dependencies and system files needed by the command.
- Create a new mount namespace.
- Replace the root filesystem in the new mount namespace with one that is made up of our system files copy.
- Execute the program inside the new mount namespace.
Root Filesystems
A question that arises already at step 1
is which system files are even needed by the command we want to run? We could rummage in our own root filesystem and ask this question for every file that we encounter and only include the ones where the answer is yes but that sounds painful and unnecessary. Also, we don’t even know what command isolate
will be executing to begin with.
wget http://dl-cdn.alpinelinux.org/alpine/v3.10/releases/x86_64/alpine-minirootfs-3.10.1-x86_64.tar.gz
rootfs
alpine-minirootfs-3.10.1-x86_64.tar.gz rootfs
rootfs
bin dev etc home lib media mnt opt proc root run sbin srv sys tmp usr var
The rootfs
directory has familiar files just like our own root filesystem at /
but checkout how minimal it is — quite a few of these directories are empty:
rootfs/mnt,dev,proc,home,sys
This is great! we can give the command that we launch a copy of this and it could sudo rm -rf /
for all we care, no one else will be bothered.
Pivot root
Given our new mount namespace and a copy of system files, we would like to mount those files on the root directory of the new mount namespace without pulling the rug from under our feet.
Linux has us covered here with the pivot_root
system call (there is an associated command) that allows us to control what a processes sees as the root filesystem.
The command takes two arguments pivot_root new_root put_old
where new_root
is the path to the filesystem containing the soon-to-be root filesystem and put_old
is a path to a directory. It works by:
- Mounting the root filesystem of the calling process on
put_old
. - Mounting the filesystem pointed to by
new_root
as the current root filesystem at/
.
Let’s see this in action. In our new mount namespace, we start by creating a filesystem out of our alpine files:
unshare bash
mount rootfs rootfs
Next we pivot root:
rootfs
put_old
pivot_root put_old
/
# We should now have our new root. e.g if we:
proc
# proc is empty
# And the old root is now in put_old
put_old
bin dev home lib lost+found mnt proc run srv tmp var
boot etc initrd.img lib64 media opt root sbin sys usr vmlinuz
Finally, we unmount the old filesystem from put_old
so that the nested shell cannot access it.
umount put_old
With that, we can run any command in our shell and they will run using our custom alpine root filesystem, unaware of the orchestration that led up to their execution.
And our precious files on the old filesystem are safe beyond their reach.
Implementation
The source code for this post can be found here.
We can replicate what we just accomplished in code, swapping the pivot_root
command for the corresponding system call.
First, we create our command process in a new mount namespace by adding the CLONE_NEWNS
flag to clone
.
"Failed to mount %s at %s: %m
"Failed to chdir to rootfs mounted at %s: %m
"Failed to mkdir put_old %s: %m
"Failed to pivot_root from %s to %s: %m
"Failed to chdir to new root: %m
"Failed to umount put_old %s: %m
We need to call this function from our code and it must be done by our command process in cmd_exec
(since its the one running within the new mount namespace), before the actual command begins execution.
// Wait for 'setup done' signal from the main process.
Let’s try it out:
./isolate sh
put_old
# put_old is empty. Hurray!
# What does our new mount list look like?
/proc//mounts
: cant open : No such file or directory
# Hmmm, what other processes are running?
ps aux
PID USER TIME COMMAND
# Empty! eh?
This output shows something strange — we’re unable to verify the mount list that we have fought so hard for, and ps
tells us that there are no processes running on the system (not even the current process or ps
itself?).
Its more likely that we broke something while setting up the mount namespace.
PID Namespaces
We’ve mentioned the /proc
directory a few times so far in this series and if you were familiar with it, then you’re probably not surprised that ps
came up empty since we saw earlier that the directory was empty within this mount namespace (when we got it from the alpine root filesystem).
The /proc
directory in Linux is usually used to expose a special filesystem (called the proc filesystem) that is managed by Linux itself.
Linux uses it to expose information about all processes running in the system as well as other system information with regards to devices, interrupts etc.
Whenever we run a command like ps
which accesses information about processes in the system, it looks to this filesystem to fetch information.
In other words, we need to spin up a proc
filesystem.
Luckily, this basically involves telling Linux that we need one, preferably mounted at /proc
. But we can’t do so just yet since our command process is still dependent on the same proc
filesystem as isolate
and every other regular process in the system — to cut this dependency, we need to run it inside its own PID
namespace.
We can create a new PID namespace by passing the CLONE_NEWPID
to clone
:
Next, we add a function prepare_procfs
that sets up the proc filesystem by mounting one within the currently mount and pid namespace.
"Failed to mkdir /proc: %m
"Failed to mount proc: %m
Finally, we call the function right before unmounting put_old
in our prepare_mntns
function, after we have setup the mount namespace and changed to the root directory.
"Failed to umount put_old %s: %m
We can take isolate
for another spin:
This looks much better! The shell sees itself as the only process running on the system and running as PID 1 (since it was the first process to start in this new PID namespace).
This post covered two namespaces and isolate
racked up two new features as a result. In the next post, we will be looking at isolation via Network
namespaces. There, we will have to deal with some intricate, low-level network configuration in an attempt to enable network communication between processes in different network namespaces.
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Вопрос по Mount Point’ам в Линуксе
Всем доброго времени суток. Подскажите пожалуйста новичку для чего нужна каждая из нижеперечисленных mount point’ов:
/root
/home
/var
/mnt/windows
/opt
/tmp
/usr/local
/var/ftp
/var/www
И сколько под каждую из них надо выделять места.
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
LightFalcon
- Сообщения: 323
- Статус: Любитель Free…
- ОС: Debian Squezee\Etch\Lenny
- Контактная информация:
Re: Вопрос по Mount Point’ам в Линуксе
02.05.2007 12:20
А вообще если не знаешь как разбить hard разбивай так: 10-15 гигов под / (корень) и сколько захочешь под /home
-
diesel
- Бывший модератор
- Сообщения: 5989
- ОС: OS X, openSuSE, ROSA, Debian
- Контактная информация:
Re: Вопрос по Mount Point’ам в Линуксе
02.05.2007 12:30
Trojan писал(а): ↑
Всем доброго времени суток. Подскажите пожалуйста новичку для чего нужна каждая из нижеперечисленных mount point’ов:
/root
/home
/var
/mnt/windows
/opt
/tmp
/usr/local
/var/ftp
/var/wwwИ сколько под каждую из них надо выделять места.
http://www.pathname.com/fhs/
вот тут про то зачем они нужны(ну кроме /mnt/windows )
-
diesel
- Бывший модератор
- Сообщения: 5989
- ОС: OS X, openSuSE, ROSA, Debian
- Контактная информация:
Re: Вопрос по Mount Point’ам в Линуксе
02.05.2007 12:35
Liksys писал(а): ↑
От 100%, что вопрос с теста в универе.
очень странный тест в таком случае. т.к. для описания трех директорий из списка вполне применим ответ «все что угодно»)
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Re: Вопрос по Mount Point’ам в Линуксе
02.05.2007 13:27
alv писал(а): ↑
Если Вы точно не знаете, для чего они нужны — они Вам не нужны. Ограничтесь для начала двумя — корнем (/) и /home.
LightFalcon писал(а): ↑
А вообще если не знаешь как разбить hard разбивай так: 10-15 гигов под / (корень) и сколько захочешь под /home
Дело в том что не зная для нужен каждый раздел я выделял всем разделам по 3 гига. В итоге нехватало места для всех компонентов и я не знал для какого раздела выделить больше пространства так чтобы были установлены все компоненты. Отсюда и родился такой вопрос.
Если я создам при установке только /root и /home, смогу ли я потом создать другие разделы?
P.S. Кстати, заметил что также есть разделы /boot и просто /. Если не трудно дайте объяснение и этим двум разделам.
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
Uncle_Theodore
- Сообщения: 3339
- ОС: Slackware 12.2, ArchLinux 64
Re: Вопрос по Mount Point’ам в Линуксе
02.05.2007 13:33
Trojan писал(а): ↑
Если я создам при установке только /root и /home, смогу ли я потом создать другие разделы?
P.S. Кстати, заметил что также есть разделы /boot и просто /. Если не трудно дайте объяснение и этим двум разделам.
-
alv
- Бывший модератор
- Сообщения: 7268
- Статус: Пенсионер в законе
- ОС: Cintu
- Контактная информация:
Re: Вопрос по Mount Point’ам в Линуксе
02.05.2007 14:27
Uncle_Theodore писал(а): ↑
Для / достаточно 6 — 10 гиг, остальное можно пустить на /home
swap — 1 гиг достаточно для всех разумных целей.
+1 с оговоркой: если места на диске много, оставьте неразмеченным несколько гигабайт. Даст свободу маневра, когда
Uncle_Theodore писал(а): ↑
будете делать красиво…
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Re: Вопрос по Mount Point’ам в Линуксе
06.12.2007 15:33
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
uptime
- Сообщения: 1661
- Статус: Drinker with computing problems
- ОС: kubuntu 8.04
Re: Вопрос по Mount Point’ам в Линуксе
06.12.2007 15:47
А ещё советую почитать man hier
The answer, my friend, is blowin’ in the wind.
The answer is blowin’ in the wind.
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Re: Вопрос по Mount Point’ам в Линуксе
20.03.2008 20:39
При установке RHEL 4 на стадии разбиения диска, зашел в Mount Point и оказалось, что нет некоторых Mount Point’ов, которые есть в других дистрибутивах. Сделал вывод что четкой привязки Mount Point’а к стипу сервера нет. Т.е. чтобы поднять вэб сервак не обязательно создавать /var/www или /var/ftp для FTP сервера. Вот только как насчет монтировки виндовых разделов или в новых дистрибутивах виндовые разделы видятся без монтирования?
- Вложения
-
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
Black
- Сообщения: 1100
- ОС: ArchLinux
Re: Вопрос по Mount Point’ам в Линуксе
20.03.2008 22:07
(Trojan) писал(а):Сделал вывод что четкой привязки Mount Point’а к стипу сервера нет.
Не совсем понял смысл фразы. Обязательно создавать только / (корневой раздел), и весьма рекомендуется swap. Отдельная точка монтирования может понадобится если нужно использовать другую файловую систему, ФС с нестандартными параметрами или опциями монтирования, и т.д. А насчёт «монтировки» виндовых разделов — видимо имелось в виду монтирование, т.к. монтировка — это несколько другое. Виндовые разделы (а также и не виндовые) видятся без монтирования и в старых дистрибутивах. Монтирование нужно чтобы ОС могла обращаться к файловой системе раздела. Если это имелось в виду, то такого нет. Бывает, что виндовые разделы автоматически заносятся в fstab при установке. Кстати, может перед установкой почитать?
Компьютер служит для решения тех проблем, которых до изобретения компьютера не существовало
-
Rootlexx
- Бывший модератор
- Сообщения: 4443
- Статус: GNU generation
- ОС: Debian GNU/Linux
Re: Вопрос по Mount Point’ам в Линуксе
20.03.2008 22:07
Trojan писал(а): ↑
При установке RHEL 4 на стадии разбиения диска, зашел в Mount Point и оказалось, что нет некоторых Mount Point’ов, которые есть в других дистрибутивах. Сделал вывод что четкой привязки Mount Point’а к стипу сервера нет. Т.е. чтобы поднять вэб сервак не обязательно создавать /var/www или /var/ftp для FTP сервера. Вот только как насчет монтировки виндовых разделов или в новых дистрибутивах виндовые разделы видятся без монтирования?
Вы, видимо, не совсем понимаете смысл точек монтирования. Это не какие-то предопределённые точки, это просто папки на разделе жёсткого диска. Их имена могут быть любыми. Монтирование — это, если говорить упрощённо, отображение содержимого монтируемого устройства на папку. То есть при заходе в папку запрос файла «переадресуется» на то устройство, которое смонтировано (синоним — «подключено») на данную папку. Эта схема позволяет выделять определённые файловые области на другие разделы, а то и вообще по сети, причём ни одна программа, работающая с файлами, этого не заметит: ведь визуально файлы находятся («отображены») в той же самой папке, что и раньше. Поэтому работа с файлами становится прозрачной относительно их фактического расположения.
Скажем, в офисе можно для экономии места на жёстких дисках выделить под /usr, куда устанавливаются программы, отдельный раздел на одной машине, а на других машинах — подмонтировать этот раздел (по сети) в их локальный пустой /usr. И при открытии, скажем, /usr/bin/gcc произойдёт обращение к тому файлу, что расположен на той самой единственной машине.
Для функционирования системы требуется лишь один раздел — /. Причём этот самый / — тоже точка монтирования. Остальные точки монтирования опциональны. Скажем, как уже здесь упоминалось, бывает удобно выделить под /home отдельный раздел, что позволит:
1. В случае наличия нескольких Linux — использовать одну домашнюю папку пользователя вместо локальной копии в каждой системе.
2. В случае переустановки ОС — не потерять пользовательские настройки и личные файлы: ведь форматировать нужно будет только / (корень).
Поэтому если вы сделаете, скажем, /var/www точкой монтирования для отдельного раздела — все файлы будут храниться на том разделе. Если не сделаете — те же файлы будут храниться на разделе корня. Но для Apache никакой разницы в процессе доступа не будет (если для монтируемого раздела не указаны особые параметры, разумеется; это, кстати, может служить безопасности: папку временных файлов /tmp можно выделить отдельным разделом, смонтировав его потом с параметром noexec, что запретит запуск программ с данного раздела, а значит, и со всей папки).
Рекомендую почитать это.
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Re: Вопрос по Mount Point’ам в Линуксе
21.03.2008 06:28
Black писал(а): ↑
(Trojan) писал(а):Сделал вывод что четкой привязки Mount Point’а к стипу сервера нет.
Не совсем понял смысл фразы.
Просто товарищ, которого я цитировал четко отписал:
/var/ftp — ftp-сервер
/var/www — web-сервер
а для те кто в Линуксе новичок, могут поянть это как «раз надо поднять вэб сервер, то необходимо создать /var/www. Я по началу так и понял
Black писал(а): ↑
А насчёт «монтировки» виндовых разделов — видимо имелось в виду монтирование, т.к. монтировка — это несколько другое. Виндовые разделы (а также и не виндовые) видятся без монтирования и в старых дистрибутивах. Монтирование нужно чтобы ОС могла обращаться к файловой системе раздела. Если это имелось в виду, то такого нет. Бывает, что виндовые разделы автоматически заносятся в fstab при установке.
Имелось ввиду следующее (опять же со слов знающих людей):
/mnt/windows — сюда монтируются другие разделы, в твоем случае раздел на котором стоит windows
Я так понял что этот поинт позволяет из Линукса обращаться к файловой системе Windows. Именно такой mount point можно было создать при установка Mandrake 10 (в моем случае). Сейчас пробую установить Red Hat Enterprise 4 и вот там при редактировании партиций и всего что с этим связано создание такого поинта не предусмотрено (см. картинку). Отсюда и был вопрос про монтирование виндовых разделов. Я так понял, что раз нет такого поинта, значит к виндовым разделы можно будет обращаться без него.
2 Rootlexx — благодарю за разъяснение и ссылку.
Вопрос в догону — почитав литературу я так понял, что после установки, эти mount point’ы можно добавлять причем называть их можно как угодна. Так?
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
diesel
- Бывший модератор
- Сообщения: 5989
- ОС: OS X, openSuSE, ROSA, Debian
- Контактная информация:
Re: Вопрос по Mount Point’ам в Линуксе
21.03.2008 10:07
Trojan писал(а): ↑
Вопрос в догону — почитав литературу я так понял, что после установки, эти mount point’ы можно добавлять причем называть их можно как угодна. Так?
да. т.е. говоря другими словами ты можешь создать папку с любым понравившимся названием, и смонтировать в нее любой не смонтированный раздел, или другую папку.
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Re: Вопрос по Mount Point’ам в Линуксе
25.03.2008 06:27
Прошелся я тут по литературе касательно точек монтирования. Прошу экспертов меня подправить если я че не так понял.
1) Точки монтирования можно создать на отдельных разделах, а можно создать один / и при установке все точки будут установлены туда, НО в случае падения Линукса теряются все данные.
2)
Корень: / — cамый важный раздел. И не только потому, что он содержит критически важную информацию и программы для системы, он также является и точкой монтирования для других разделов
/ или корень — это что то вроде WINDOWS в ОС Windows, только без Program Files и Document and Settings.
3)
Требования к размеру корневого раздела не слишком велики — 400МБ будет вполне достаточно. Однако, если вы планируете устанавливать коммерческие приложения, которые зачастую размещаются в каталоге /opt, вам понадобится соответственно увеличить и размер корневого раздела.
/opt — это что вроде Program Files
4)
/home — содержит личные каталоги всех пользователей вашей системы. Размер раздела зависит от количества пользователей и их потребностей.
Каталог /usr является главным каталогом для хранения приложений.
/usr — аналог Program Files.
Вопрос: так что же все таки является каталогом хранения приложений и куда устанавливаются приложения — /opt или /usr?
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
romuil
- Сообщения: 2095
- Статус: Ромунцель
- ОС: ALTLinux Sisyphus
Re: Вопрос по Mount Point’ам в Линуксе
25.03.2008 09:25
-
anjolio
- Сообщения: 663
- Статус: радист
- ОС: debian squeeze
Re: Вопрос по Mount Point’ам в Линуксе
25.03.2008 12:03
Trojan писал(а): ↑
1) Точки монтирования можно создать на отдельных разделах, а можно создать один / и при установке все точки будут установлены туда, НО в случае падения Линукса теряются все данные.
Точка монтирования — это адрес к папке. После команды монтирования устройства dev в папку fld в папке fld появляется все содержимое устройства dev. Например этим устройством был раздел с установленным линуксом, а папкой была /. Тогда у вас появится полноценная файловая структура, необходимая для работы linux. При этом все, что было до этого в папке fld становится невидимым до отмонтирования устройства dev.
Таким образом точки монтирования создаются не на разделах. Вообще они не создаются как-то специально кроме команды создания папки. Точка монтирования это просто адрес к папке. Вот советую: Wiki: Точка монтирования.
И вообще от себя добавлю — если я даже примерно не понимаю о чем идет речь, то читаю сначала википедию про это дело. Там по крайней мере довольно часто дается полное определение всех понятий. Но не стоит увлекаться — википедия, она для школьников, большинство подробных и углубленных технических вещей, после понимания базиса сущности стоит искать уже в специализированной литературе, например, в мануалах
Trojan писал(а): ↑
/ или корень — это что то вроде WINDOWS в ОС Windows, только без Program Files и Document and Settings.
Немного не так, скорее уж можно провести аналогию, что корень / это C:\\ (вроде так это пишется). Но опять же, выше уже все сказали про windows.
Trojan писал(а): ↑
5) /home я так понял аналог Documents and Settings, а /home/username — Documents and Settings/Username
Почти так. Только в windows дальше идет дробление на специальные каталоги, а в linux нет. Привожу пример: большинство пользовательских настроек программ в windows xp лежали у меня в documents and settings/anjolio/application cache, а в линуксе ВСЕ настройки лежат в корне домашнего каталога (хомяка от home): в /home/anjolio. Это ни коим образом не мешает вашей работе, т.к. все эти файлы и папки с настройками являются скрытыми (перед именем стоит точка).
Trojan писал(а): ↑
Вопрос: так что же все таки является каталогом хранения приложений и куда устанавливаются приложения — /opt или /usr?
Если вы сами принудительно не ставите куда-либо в другое место, то 4 каталога: /sbin, /bin, /usr/sbin, /usr/bin.
The two most common things in the Universe are hydrogen and stupidity. (Harlan Ellison)
-
Trojan
- Сообщения: 359
- Статус: Системный ламер
- ОС: CentOS 7
Re: Вопрос по Mount Point’ам в Линуксе
06.11.2008 20:56
Имеет ли значение куда определять раздел, в начало или в конец?
Если имеет, то какие разделы нужно устанавливать в начале, а какие в конце?
И еще, какие разделы должны быть основными (primary), а какие логическими (logical)?
Всегда думай то, что говоришь и никогда не говори то, что думаешь.
-
uptime
- Сообщения: 1661
- Статус: Drinker with computing problems
- ОС: kubuntu 8.04
Re: Вопрос по Mount Point’ам в Линуксе
07.11.2008 00:25
Trojan писал(а): ↑
Имеет ли значение куда определять раздел, в начало или в конец?
Если имеет, то какие разделы нужно устанавливать в начале, а какие в конце?
И еще, какие разделы должны быть основными (primary), а какие логическими (logical)?
1) Я для себя такую схему определил: корень, swap, home. Так получается оптимальнее, по крайней мере поначалу, пока home не заполнился.
2) Логические разделы адресуются по цепочке. Поэтому для них вероятность потери данных выше, чем для первичных. По крайней мере теоретически.
The answer, my friend, is blowin’ in the wind.
The answer is blowin’ in the wind.
-
Goodvin
- Ведущий рубрики
- Сообщения: 4333
- Статус: ⚝⚠⚒⚑⚖☭☞☣☤&
Re: Вопрос по Mount Point’ам в Линуксе
07.11.2008 07:16
anjolio писал(а): ↑
Trojan писал(а): ↑
/ или корень — это что то вроде WINDOWS в ОС Windows, только без Program Files и Document and Settings.
Немного не так, скорее уж можно провести аналогию, что корень / это C:\\ (вроде так это пишется).
А у меня на одной машине диск С:\ содержит другую операционную систему, НЕ-windows, а на другой машине диска С:\ вообще нет. Где же у меня там «аналогия корня» ? :-)))
Если уж на то пошлО — то в винде аналогом корня является такая несколько абстрактная вешь, как «Мой компьютер».
Именно внутри него содержатся объекты, именуемые буквами дисков и являющиеся точками монтирования для файловых систем.
-
Portnov
- Модератор
- Сообщения: 1786
- Статус: Матёрый линуксоид
- ОС: Debian testing/unstable
- Контактная информация:
Re: Вопрос по Mount Point’ам в Линуксе
07.11.2008 15:23
-
Rootlexx
- Бывший модератор
- Сообщения: 4443
- Статус: GNU generation
- ОС: Debian GNU/Linux
Re: Вопрос по Mount Point’ам в Линуксе
08.11.2008 00:18
Portnov писал(а): ↑
В виндах корень есть. Его обычными средствами не видно, но многие программы понимают пути такого вида: \\?\C:\Windows…. (если не ошибся, давно уже виндов не видел). Вот этот \\? — это и есть виндовый аналог /.
Насколько я помню, «\??\».