## Unit相關命令
**Systemd可以管理所有系統資源。不同的資源統稱為Unit(單位),Unit一共分成12種。**
~~~
Service unit:系統服務
Target unit:多個Unit構成的一個組
Device Unit:硬件設備
Mount Unit:文件系統的掛載點
Automount Unit:自動掛載點
Path Unit:文件或路徑
Scope Unit:不是由Systemd啟動的外部進程
Slice Unit:進程組
Snapshot Unit:Systemd快照,可以切回某個快照
Socket Unit:進程間通信的socket
Swap Unit:swap文件
Timer Unit:定時器
~~~
**systemctl list-units命令可以查看系統的所有Unit信息。**
列出已啟動的Unit
`systemctl list-units`
列出所有Unit,包括沒有找到配置文件的或者啟動失敗的
`systemctl list-units --all`
列出所有沒有啟動的Unit
`systemctl list-units --all --state=inactive`
列出所有啟動失敗的Unit
`systemctl list-units --failed`
列出所有正在運行的、類型為service的Unit
`systemctl list-units --type=service`
**systemctl status命令用于查看系統狀態和單個Unit的狀態。**
顯示系統狀態
`systemctl status`
顯示單個 Unit 的狀態
`sysystemctl status httpd.service`
顯示遠程主機的nginx服務的狀態
`systemctl -H root@192.168.2.204 status nginx.service`
除了status外,systemctl還提供了三個查詢狀態的簡單方法,主要供腳本內部的判斷語句使用。
顯示某個 Unit 是否啟動
`systemctl is-active application.service`
顯示某個 Unit 是否啟動失敗
`systemctl is-failed application.service`
顯示某個 Unit 服務是否開機啟動
`systemctl is-enabled application.service`
**systemctl常用命令**
立即啟動一個服務
`systemctl start httpd.service`
立即停止一個服務
`systemctl stop httpd.service`
重啟一個服務
`systemctl restart httpd.service`
殺死一個服務的所有子進程
`systemctl kill httpd.service`
重新加載一個服務的配置文件
`systemctl reload httpd.service`
重載所有修改過的配置文件
`systemctl daemon-reload`
顯示某個 Unit 的所有底層參數
`systemctl show httpd.service`
顯示某個 Unit 的指定屬性的值
`systemctl show -p CPUShares httpd.service`
設置某個 Unit 的指定屬性
`systemctl set-property httpd.service CPUShares=500`
Unit的后綴名.service可以省略,例如啟動ssh的命令systemctl start sshd.service可以寫成systemctl start sshd。
Unit之間存在依賴關系,A依賴于B,就意味著systemd在啟動A的時候,同時會去啟動B。
**systemctl list-dependencies命令列出一個Unit的所有依賴。**
`systemctl list-dependencies nginx.service`
上面命令的輸出結果之中,有些依賴是Target類型,默認不會展開顯示。如果要展開Target,就需要使用--all參數。
`systemctl list-dependencies --all nginx.service`
**systemctl list-unit-files命令用于列出所有Unit的狀態。**
列出所有Unit狀態
`systemctl list-unit-files`
列出指定類型的Unit狀態
`systemctl list-unit-files --type=service`
Unit的四種狀態
~~~
enabled:開機啟動
disabled:不開機啟動
static:該Unit沒有[Install]部分(無法執行),只能作為其他Unit的依賴
masked:該Unit被禁止開機啟動
~~~
如果修改了某個服務的配置文件,就要重新加載配置,然后重新啟動,否則修改不會生效。
~~~
systemctl daemon-reload
systemctl restart httpd.service
~~~
**系統運行模式target相關命令**
查看當前系統的所有Target
`systemctl list-unit-files --type=target`
查看一個 Target 包含的所有Unit
`systemctl list-dependencies multi-user.target`
查看啟動時的默認Target
`systemctl get-default`
設置啟動時的默認Target
`systemctl set-default multi-user.target`
切換Target時,默認不關閉前一個Target啟動的進程,systemctl isolate命令改變這種行為,關閉前一個Target里面所有不屬于后一個Target的進程
`systemctl isolate multi-user.target`