Linux系统中 service 和 systemctl 命令比较

2022-10-03 556点热度 0人点赞 0条评论

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

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

一、service 命令

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

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

option 的值:

  • -h:显示 service 的帮助信息
  • -status:显示所服务的状态
  • --status-all:查看所有服务的状态
  • service_name:服务名,即 /etc/init.d 目录下的脚本文件名
  • command:系统服务脚本支持的控制命令,如:start、stop 和 restart
  • --full-restart:重启所有服务

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

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

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

这种方式有如下缺点:

  • 启动时间长。init 进程是串行启动,只有前一个进程启动完,才会启动下一个进程。
  • 启动脚本复杂。init进程只是执行启动脚本,不管其他事情。脚本需要自己处理各种情况,这往往使得脚本变得很长。

查看所有的服务状态:

[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)的缩写。

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

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

三、service 与 systemctl 命令对比

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

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论