2018年2月23日 星期五

mount bind

The bind mounts.
Since Linux 2.4.0 it is possible to remount part of the file hierarchy somewhere else. The call is
   mount --bind olddir newdir

remount 只能將當前的掛載點重新掛載;
bind mounts 則可以掛載檔案系統下的檔案目錄,不受限於掛載點

# mkdir dir1 dir2
# touch dir1/dir1_foo
# touch dir2/dir2_foo
# ls -li -R
1177191 drwxr-xr-x 2 root root 4096 Feb 23 07:11 dir1
1177192 drwxr-xr-x 2 root root 4096 Feb 23 07:12 dir2
./dir1:
1085818 -rw-r--r-- 1 root root 0 Feb 23 07:11 dir1_foo
./dir2:
1085819 -rw-r--r-- 1 root root 0 Feb 23 07:12 dir2_foo

###################
# mount -o bind,ro dir1 dir2
mount: warning: dir2 seems to be mounted read-write.
# mount -o bind,ro,remount dir1 dir2
# mount | grep dir2
/home/bh0322/workspace/mount/dir1 on /home/bh0322/workspace/mount/dir2 type none (ro,bind)
在系統就永遠找不到dir2_foo這個檔案了,除非umount dir2

# ls -li -R
1177191 drwxr-xr-x 2 root root 4096 Feb 23 07:11 dir1
1177191 drwxr-xr-x 2 root root 4096 Feb 23 07:11 dir2
./dir1:
1085818 -rw-r--r-- 1 root root 0 Feb 23 07:11 dir1_foo
./dir2:
1085818 -rw-r--r-- 1 root root 0 Feb 23 07:11 dir1_foo

###################
Symbolic link
1. symbolic link 有自己的 inode、檔案和屬性等
2. 可以對不存在的檔案或目錄建立 symbolic link
3. 可以對不同檔案系統或掛載點下的檔案或目錄建立 symbolic link
4. 刪除 symbolic link 不會影響被連結的檔案或目錄;但如果連結的檔案或目錄被删除,symbolic link 會存取錯誤

Hard link
1. 跟被連結的檔案或目錄有相同的 inode、檔案 和屬性等
2. 只能對存在的文件檔案或目錄建立 hard link
3. 不能對不同檔案系統或掛載點下的檔案或目錄建立 hard link
4. 不能目錄建立 hard link
5. 删除 hard link 不會影響被連結的檔案或目錄;但如果連結的檔案或目錄被删除,hard link 仍然可以讀寫
# ln -s dir1 dir3
# ln dir1 dir4
ln: ‘dir1’: hard link not allowed for directory
# ls -li -R
1177191 drwxr-xr-x 2 root root 4096 Feb 23 07:11 dir1
1177191 drwxr-xr-x 2 root root 4096 Feb 23 07:11 dir2
393735 lrwxrwxrwx 1 root root    4 Feb 23 07:12 dir3 -> dir1
./dir1:
1085818 -rw-r--r-- 1 root root 0 Feb 23 07:11 dir1_foo
./dir2:
1085818 -rw-r--r-- 1 root root 0 Feb 23 07:11 dir1_foo

###################
# rm -rf dir2
rm: cannot remove ‘dir2’: Device or resource busy
裡面的檔案都被rm只剩dir2
rm: cannot remove ‘dir2/dir1_foo’: Read-only file system

在 Linux 是可以的。但 bind mount 檔案或 bind mount 到 的 徑上有 麼優點?前 說到 bind mounts 跟 hard link 很像,但 bind mounts 是掛載。除 沒有卸載無法刪除以外,也同樣可以使  mount 的 option, 如:ro、noexec、nouser、nosuid 等,在檔案系統的權限外多增加 增保護。

###################
# strace ln a.txt c.txt
symlink("a.txt", "b.txt")               = 0

# strace ln -s a.txt b.txt
lstat("a.txt", {st_mode=S_IFREG|0664, st_size=6, ...}) = 0
linkat(AT_FDCWD, "a.txt", AT_FDCWD, "c.txt", 0) = 0

參考資料:
https://lwn.net/Articles/281157/
https://wiki.archlinux.org/index.php/Fstab_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)