本文將比較 linux 中 service 和 systemctl 命令,先分別簡(jiǎn)單介紹這兩個(gè)命令的基礎(chǔ)用法,然后進(jìn)行比較。
從 centos 7.x 開(kāi)始,CentOS 開(kāi)始使用 systemd 服務(wù)來(lái)代替 service服務(wù)(daemon),原來(lái)管理系統(tǒng)啟動(dòng)和管理系統(tǒng)服務(wù)的相關(guān)命令全部由 systemctl命令來(lái)代替。
一、service 命令
service命令是Redhat Linux兼容的發(fā)行版中用來(lái)控制系統(tǒng)服務(wù)的實(shí)用工具,它以啟動(dòng)、停止、重新啟動(dòng)和關(guān)閉系統(tǒng)服務(wù),還可以顯示所有系統(tǒng)服務(wù)的當(dāng)前狀態(tài)。
語(yǔ)法: service < option > | --status-all | [ service_name [ command | --full-restart ] ]
option 的值:
- -h:顯示 service 的幫助信息
- -status:顯示所服務(wù)的狀態(tài)
- --status-all:查看所有服務(wù)的狀態(tài)
- service_name:服務(wù)名,即 /etc/init.d 目錄下的腳本文件名
- command:系統(tǒng)服務(wù)腳本支持的控制命令,如:start、stop 和 restart
- --full-restart:重啟所有服務(wù)
可以理解成 service 就是init.d 的一種實(shí)現(xiàn)方式。
所以這兩者啟動(dòng)方式(或者是停止、重啟)并沒(méi)有什么區(qū)別。
$ sudo /etc/init.d/Nginx start
// 等價(jià)于
$ service nginx start
這種方式有如下缺點(diǎn):
- 啟動(dòng)時(shí)間長(zhǎng)。init 進(jìn)程是串行啟動(dòng),只有前一個(gè)進(jìn)程啟動(dòng)完,才會(huì)啟動(dòng)下一個(gè)進(jìn)程。
- 啟動(dòng)腳本復(fù)雜。init進(jìn)程只是執(zhí)行啟動(dòng)腳本,不管其他事情。腳本需要自己處理各種情況,這往往使得腳本變得很長(zhǎng)。
查看所有的服務(wù)狀態(tài):
[root@centos-160 ~]# service --status-all
/var/run/clickhouse-server/clickhouse-server.pid file exists and contains pid = 1192.
The process with pid = 1192 is running.
顯示系統(tǒng)當(dāng)前的clickhouse進(jìn)程狀態(tài),可以看到pid是一致的。
[root@centos-160 ~]# ps -ef | grep clickhouse
clickho+ 935 1 0 08:58 ? 00:00:00 clickhouse-watchdog --config=/etc/clickhouse-server/config.xml --pid-file=/run/clickhouse-server/clickhouse-server.pid
clickho+ 1192 935 3 08:58 ? 00:00:03 /usr/bin/clickhouse-server --config=/etc/clickhouse-server/config.xml --pid-file=/run/clickhouse-server/clickhouse-server.pid
root 1698 1661 0 08:59 pts/0 00:00:00 grep --color=auto clickhouse
二、systemctl 命令
在較新的linux系統(tǒng)上,都使用systemd 取代了init,成為系統(tǒng)的第一個(gè)進(jìn)程(PID 等于 1),其他進(jìn)程都是它的子進(jìn)程。systemd為系統(tǒng)啟動(dòng)和管理提供了完整的解決方案。它提供了一組命令。字母d是守護(hù)進(jìn)程(daemon)的縮寫(xiě)。
查看systemd 的版本:
[root@centos-160 ~]# systemctl --version
systemd 239 (239-45.el8)
+PAM +AUDIT +SELINUX +IMA -AppARMOR +SmacK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN2 -IDN +PCRE2 default-hierarchy=legacy
列出所有服務(wù)(包括啟用和禁用):
# systemctl list-unit-files --type=service
systemd 的優(yōu)點(diǎn)是功能強(qiáng)大,使用方便;缺點(diǎn)是體系龐大,非常復(fù)雜。事實(shí)上,現(xiàn)在還有很多人反對(duì)使用 systemd,理由就是它過(guò)于復(fù)雜,與操作系統(tǒng)的其他部分強(qiáng)耦合,違反 “keep simple, keep stupid” 的Unix 哲學(xué)。
三、service 與 systemctl 命令對(duì)比
下面是service和systemctl命令格式對(duì)比:






