本文将比较 Linux 中 service 和 systemctl 命令,先分别简单介绍这两个命令的基础用法,然后进行比较。

从 centos 7.x 开始,CentOS 开始使用 systemd 服务来代替 service服务(daemon),原来管理系统启动和管理系统服务的相关命令全部由 systemctl命令来代替。

linux有几种运行模式(Linux中service和)(1)

一、service 命令

service命令是Redhat Linux兼容的发行版中用来控制系统服务的实用工具,它以启动、停止、重新启动和关闭系统服务,还可以显示所有系统服务的当前状态。

语法: service < option > | --status-all | [ service_name [ command | --full-restart ] ]

option 的值:

可以理解成 service 就是init.d 的一种实现方式。

所以这两者启动方式(或者是停止、重启)并没有什么区别。

$ sudo /etc/init.d/nginx start // 等价于 $ service nginx start

这种方式有如下缺点:

查看所有的服务状态:

[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.

显示系统当前的clickhouse进程状态,可以看到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系统上,都使用systemd 取代了init,成为系统的第一个进程(PID 等于 1),其他进程都是它的子进程。systemd为系统启动和管理提供了完整的解决方案。它提供了一组命令。字母d是守护进程(daemon)的缩写。

linux有几种运行模式(Linux中service和)(2)

查看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

列出所有服务(包括启用和禁用):

# systemctl list-unit-files --type=service

linux有几种运行模式(Linux中service和)(3)

systemd 的优点是功能强大,使用方便;缺点是体系庞大,非常复杂。事实上,现在还有很多人反对使用 systemd,理由就是它过于复杂,与操作系统的其他部分强耦合,违反 “keep simple, keep stupid” 的Unix 哲学。

三、service 与 systemctl 命令对比

下面是service和systemctl命令格式对比:

linux有几种运行模式(Linux中service和)(4)

,