Linux的命名空間


1. 為什么提供命名空間

命名空間是一種輕量級的虛擬化手段。

傳統的虛擬化軟件,是虛擬化多個不同的操作系統,對共享資源的限制很大。

通過提供命名空間,可以讓進程與進程之間,用戶與用戶之間彼此看不到對方。

命名空間,相當於容器。

命名空間,本質上建立了系統的不同視圖。

 

chroot是一種簡單的命名空間,僅限於將進程限制在文件系統的某一部分。

2. 創建命名空間的方式

1). fork/clone創建新進程時,可以設置選項,使新進程與父進程共享命名空間,還是新進程創建一個獨立的命名空間。

2). unshare系統調用,可以將進程的某些部分從父進程分離,其中也包括命名空間。

 

3. 實現:

   1: struct task_struct {
   2: ......
   3: /* namespaces */
   4:     struct nsproxy *nsproxy;
   5: ......
   6: }
   1: /*
   2:  * A structure to contain pointers to all per-process
   3:  * namespaces - fs (mount), uts, network, sysvipc, etc.
   4:  *
   5:  * 'count' is the number of tasks holding a reference.
   6:  * The count for each namespace, then, will be the number
   7:  * of nsproxies pointing to it, not the number of tasks.
   8:  *
   9:  * The nsproxy is shared by tasks which share all namespaces.
  10:  * As soon as a single namespace is cloned or unshared, the
  11:  * nsproxy is copied.
  12:  */
  13: struct nsproxy {
  14:     atomic_t count;
  15:     struct uts_namespace *uts_ns;
  16:     struct ipc_namespace *ipc_ns;
  17:     struct mnt_namespace *mnt_ns;
  18:     struct pid_namespace *pid_ns;
  19:     struct net          *net_ns;
  20: };

每個進程都有一個指針指向nsproxy結構體,多個進程可能共享一個nsproxy結構體,比如父子進程。

一個nsproxy代表一整套的命名空間實現,其中包含了幾個子系統的命名空間:

UTS(UNIX Timesharing System),包含了運行內核的名稱,版本,底層體系結構的信息;

IPC,包含了所有與進程間通信有關的信息;

MNT,包含了文件系統的視圖;

PID,就是進程ID;

USER,就是用戶;

NET,與網絡相關。

各個子系統對於命名空間的實現與應用都各不相同。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM