Linux啓動程序systemd和環境變量

昨天看到一篇文章,講的是Linux的開機啓動,個人感覺寫得非常好。我是在學習環境變量時看到的,所以只翻譯其中的一小部分,再結合環境變量講一講。建議大家好好讀一下原文。

systemd

Linux系統的開機流程(boot process)的結束:選定的系統核(kernel)加載到內存,然後解壓自己,加載systemd,此時控制權交給了systemd,開始系統的啓動流程(startup process)。
截至上面的步驟完成,只有核和systemd在運行,什麼都做不了,需要systemd去完成接下來的工作,完成時Linux主機纔會是可用狀態。
systemd是所有進程的父進程或者祖先進程,它的pid是1。第一步,它會加載定義在/etc/fstab中的文件系統,加載後就可以訪問位於/etc中的配置文件,它的配置文件/etc/systemd/system/default.target會告訴它該使用哪個target去完成接下來的工作。
target和service是systemd中的基本單元。target是一組service的組合,選擇某個target後就要去啓動相應的一些服務。
target的作用就是定義啓動方式。舉例來說,想在啓動後進入圖形界面模式,target就選擇graphical.target,想在啓動後進入命令行模式,target就選mutil-user.target,分別對應舊版本/etc/inittab文件中的level5和level3。
target對應一系列服務,我們自定義systemd服務時需要定義/usr/lib/systemd/system/myservice.service文件,在[Install]中要用WantedBy=來定義該服務用於哪個target。當target對應的所有服務都啓動起來之後,Linux系統就處於那個target level了。

環境變量

“In all Unix and Unix-like systems, each process has its own separate set of environment variables. By default, when a process is created, it inherits a duplicate environment of its parent process, except for explicit changes made by the parent when it creates the child.”—來自維基百科

從上面可以看到,環境變量是和進程相關的,子進程可以繼承父進程的環境變量,也可以顯式地指定自己的環境變量,子進程設置的環境變量不會影響父進程的環境變量。

shell的環境變量也是shell的進程的環境變量,在shell中運行程序時,那些程序的進程是shell進程的子進程,會繼承shell進程的環境變量。

因爲systemd是所有進程的父進程或祖先進程(ancestor process),所以它的環境變量會被所有的進程所繼承,systemd進程的環境變量可以在/etc/systemd/system.conf設置,語法爲DefaultEnvironment=,DefaultEnvironment="test=test"會添加值爲test的環境變量test。當我們自己添加系統服務時,也可以在/etc/systemd/system/myservice.service.d中以.conf結尾的文件(一般來說是override.conf,可以直接用systemctl edit mysevice打開)中爲需要啓動的服務進程指定環境變量,語法爲Environment=,或者EnvironmentFile=,後一種方法會指定環境變量文件,適合需要設置比較多的環境變量的情況。

"/etc/environment is not a global configuration file.
It applies only on Linux; only to PAM sessions, as employed by login and so forth; and only in the case where a particular PAM plug-in is installed and enabled on the system, and where that PAM plug-in has not been configured to use some other file (because /etc/environment is merely its default if it is not told otherwise). It is that PAM plug-in that reads it.
Otherwise, it is just a meaningless file in /etc that nothing uses."以後遇到了再更新

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章