1, System service manager Systemd
Init (short for initialization) is a program used to generate all other processes in Unix and Unix like systems. After the Linux kernel is loaded and started, the first process in user space is init process. The process number of this process is 1, which represents the first running user space process. It runs as a parent daemon, and other processes in user space are its child processes.
When the Linux system loads the Linux kernel during boot, the Linux kernel loads the init program, and the init program completes the rest of the boot process, such as loading the running level, loading the service, booting the Shell / graphical interface, etc.
Systmed is a system initialization program, which is responsible for controlling and managing system services. It is actually a user space program, which belongs to the application program and does not belong to the category of Linux kernel. The main characteristics of Linux kernel are unified in all distributions, and what manufacturers can freely change is the user space application program. After the Linux system with system D as the system service manager (startup program) is started, system D is the init process.
The name system d comes from a convention in Unix: in Unix, d is often used as the suffix of the system daemon. d is the first letter of the English word daemon (meaning background process).
Different distributions use different startup procedures:
(1) The Linux distribution of Ubuntu uses Upstart.
(2) CentOS before version 7.0 of Red Hat adopts System V init.
(3) Red Hat's version 7.0 CentOS uses system D.
At present, Systemd is not only used as the system service manager in the Linux distribution of Red Hat, but other factions also begin to use Systemd as the initialization system of the latest distribution to replace the commonly used init programs of System V and BSD style.
(1) Features of system D
Start the system service in parallel when starting up, which greatly improves the starting speed of the system
Start daemons on demand
Support system state snapshot
Dependency based service control logic, automated service dependency management
Cggroup is used to track sub processes, which is clean and reliable
socket type and D-Bus type activation service are adopted at the same time
(2) Differences between system D and traditional init system
systemd replaces the concept of run level in System V init with target
The default Run Level (set in the / etc/inittab file) is now replaced by the default target by the file / etc / SYSTEMd / system / default Target definition, usually symbolic link to graphical Target (graphical interface) or multi-user Target (multi-user command line)
The location of the startup script, formerly / etc / init D directory, symbolic links to different Run Level directories (such as / etc/rc3.d, / etc/rc5.d, etc.), which are now stored in / lib/systemd/system and / etc/systemd/system directories
The location of the configuration file. Previously, the configuration file of the init process was / etc/inittab, and the configuration files of various services were stored in the / etc/sysconfig directory. The current configuration files are mainly stored in the / lib/systemd directory. The modifications in the / etc/systemd directory can overwrite the original settings
(3) System D directories and files
The file paths related to system D may be different in different distributions. Here, take ubuntu 16.04 as an example to briefly introduce as follows:
/lib/systemd/system /: most unit configuration files are placed in this directory, while CentOS is placed in / usr/lib/systemd/system /. Use the command: systemctl list unit files to list all configuration files in this directory.
/etc/systemd/system /: the main files in this directory point to the linked files in the / lib/systemd/system / directory. Note that when we create the unit configuration file ourselves, we can put the configuration file in either the / lib/systemd/system / directory or the / etc/systemd/system / directory.
/run/systemd/system /: scripts generated during system operation, such as user related scripts and session related scripts.
/Many service default configuration files are placed in the directory of / etc/default /.
/var/lib / some services that generate data will write their data into the / var/lib / directory. For example, the data files related to docker are placed in this directory.
/The bin and / sbin utility commands are located in these two directories.
/run / this directory contains many temporary data of service runtime, such as lock file, PID file, socket file, etc.
We use the command systemctl list sockets to check the location of the socket file:
[root@htlwk0001host ~]# systemctl list-sockets LISTEN UNIT ACTIVATES /run/dbus/system_bus_socket dbus.socket dbus.service /run/dmeventd-client dm-event.socket dm-event.service /run/dmeventd-server dm-event.socket dm-event.service /run/initctl systemd-initctl.socket systemd-initctl.service /run/lvm/lvmpolld.socket lvm2-lvmpolld.socket lvm2-lvmpolld.service /run/systemd/coredump systemd-coredump.socket /run/systemd/journal/dev-log systemd-journald-dev-log.socket systemd-journald.service /run/systemd/journal/socket systemd-journald.socket systemd-journald.service /run/systemd/journal/stdout systemd-journald.socket systemd-journald.service /run/udev/control systemd-udevd-control.socket systemd-udevd.service /var/run/.heim_org.h5l.kcm-socket sssd-kcm.socket sssd-kcm.service kobject-uevent 1 systemd-udevd-kernel.socket systemd-udevd.service 12 sockets listed. Pass --all to see loaded but inactive sockets, too.
Under CentOS system, we can use the command rpm -ql systemd to view the relevant directories and files of Systemd:
[root@htlwk0001host ~]# rpm -ql systemd /etc/X11/xinit/xinitrc.d/50-systemd-user.sh /etc/X11/xorg.conf.d/00-keyboard.conf /etc/binfmt.d /etc/crypttab /etc/dnf/protected.d/systemd.conf /etc/hostname /etc/inittab
The file / etc/inittab is the standard configuration file of System V init. After using system D as the init system, let's take a look at the contents of this file:
[root@htlwk0001host ~]# cat /etc/inittab # inittab is no longer used. # # ADDING CONFIGURATION HERE WILL HAVE NO EFFECT ON YOUR SYSTEM. # # Ctrl-Alt-Delete is handled by /usr/lib/systemd/system/ctrl-alt-del.target # # systemd uses 'targets' instead of runlevels. By default, there are two main targets: # # multi-user.target: analogous to runlevel 3 # graphical.target: analogous to runlevel 5 # # To view current default target, run: # systemctl get-default # # To set a default target, run: # systemctl set-default TARGET.target
As can be seen from the above, after Systemd took power, the file / etc/inittab is no longer used, and there is no concept of "run level". The active configuration file is / etc / Systemd / system / default Target this file. The contents of this document are as follows:
[root@htlwk0001host ~]# cat /etc/systemd/system/default.target # SPDX-License-Identifier: LGPL-2.1+ # # This file is part of systemd. # # systemd is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. [Unit] Description=Multi-User System Documentation=man:systemd.special(7) Requires=basic.target Conflicts=rescue.service rescue.target After=basic.target rescue.service rescue.target AllowIsolate=yes
(4) Introduction to system D Unit
The core concept of system D is unit. Unit represents different types of system D objects, which are identified and configured through configuration files. Linux distributions initialized with SysV or UpStart use the directory / etc / RC d/init. bash initialization scripts under D / are used to manage system services, while Linux distributions that use system D as the initialization system (e.g. RHEL 7.x, CentOS 7.x) replace these startup scripts with service units, which are Service, as a service file with an extension, provides the same purpose as the initialization script.
File name extension: service Service, which is used to define system services
Target: the logical grouping of units, including multiple related units, used to simulate and realize the operation level of System V
Device: used to define the device recognized by the kernel, corresponding to a device marked by udev rules
Mount: define the file system mount point, and system D will mount automatically based on it. In order to be compatible with System V init, at present, system D automatically processes / etc/fstab and converts it to mount
Socket: used to identify the socket file used for inter process communication. It can also delay the start of the service when the system is started to realize on-demand start
Snapshot: manages system snapshots, similar to Target, indicating the current running status
Swap: used to identify swap devices
Automount: the auto mount point of the file system
Path: used to define the use of a file or directory in the file system. It is often used to delay the activation of the service when the file system changes
Timer: timer, which is used to trigger user-defined operations regularly. It can be used to replace traditional atd, crond, etc
Scope: not an external process started by system D
Slice: Process Group
2. Configuration file of unit
Each Unit has a configuration file that tells system d how to start the Unit. The task of the system administrator is to write and maintain different configuration files.
Systemd reads the configuration file from the directory / etc/systemd/system / by default. However, most of the files stored inside are symbolic links, pointing to the directory / usr/lib/systemd/system /, which is the real directory where the configuration files are stored.
The suffix of the configuration file is the type of the Unit, such as sshd socket. If omitted, the default suffix of system D is Service, so sshd will be understood as sshd service.
Once the configuration file is modified, make system D reload the configuration file and restart it. Otherwise, the modification will not take effect. For example:
$ sudo systemctl daemon-reload $ sudo systemctl restart httpd.service
(1) Status of profile
There are four types:
enabled: the startup link has been established
disabled: the startup link is not established
static: this configuration file has no [Install] part (cannot be executed), and can only be used as a dependency of other configuration files
masked: this profile is prohibited from establishing a startup link
(2) Format of configuration file
A configuration file is an ordinary text file that can be opened with a text editor.
The systemctl cat command can view the contents of the configuration file.
$ systemctl cat atd.service [Unit] Description=ATD daemon [Service] Type=forking ExecStart=/usr/bin/atd [Install] WantedBy=multi-user.target
As can be seen from the above output, the configuration file is divided into several blocks. The first line of each block is the distinguished name in square brackets, such as [Unit]. Note that the block name and field name of the configuration file are case sensitive.
Inside each block are some key value pairs connected by equal signs.
[Section] Directive1=value Directive2=value . . .
Note that there should be no spaces on both sides of the equal sign of the key value pair.
(4) Block of profile
The [Unit] block is usually the first block of the configuration file, which is used to define the metadata of the Unit and configure the relationship with other units. Its main fields are as follows.
Description: short description
Documentation: document address
Requires: other units that the current Unit depends on. If they are not running, the current Unit will fail to start
Wants: other units matched with the current Unit. If they are not running, the current Unit will not fail to start
BindsTo: similar to requirements, if the specified Unit exits, the current Unit will stop running
Before: if the Unit specified in this field also needs to be started, it must be started after the current Unit
After: if the Unit specified in this field also needs to be started, it must be started before the current Unit
Conflicts: the Unit specified here cannot run simultaneously with the current Unit
Condition...: the conditions that must be met for the current Unit to run, otherwise it will not run
Assert...: the conditions that must be met for the current Unit to run. Otherwise, the startup failure will be reported
[Install] is usually the last block of the configuration file, which is used to define how to start and whether to start. Its main fields are as follows:
WantedBy: its value is one or more targets. When the current Unit is activated (enable), the symbolic link will be placed under the / etc/systemd/system directory with the name of Target + In the subdirectory composed of wants suffix
RequiredBy: its value is one or more targets. When the current Unit is activated, the symbolic link will be placed under the / etc/systemd/system directory with the name of Target + In the subdirectory composed of the required suffix
Alias: alias that the current Unit can use to launch
Also: other units that will be activated at the same time when the current Unit is activated
The [Service] block is used to configure the Service. Only units of Service type have this block. Its main fields are as follows:
Type: defines the process behavior at startup. It has the following values.
Type=simple: default value: execute the command specified by ExecStart to start the main process
Type=forking: create a child process from the parent process in the form of fork. After creation, the parent process will exit immediately
Type=oneshot: a one-time process. System D will wait for the current service to exit before continuing
Type=dbus: the current service is started through D-Bus
Type=notify: after the current service is started, Systemd will be notified, and then continue to execute
Type=idle: the current service will not run until other tasks are completed
ExecStart: command to start the current service
ExecStartPre: command executed before starting the current service
ExecStartPost: command executed after starting the current service
ExecReload: command executed when restarting the current service
ExecStop: command executed when stopping the current service
ExecStopPost: command executed after stopping its service
RestartSec: the number of seconds between automatic restart of the current service
Restart: defines when system D will automatically restart the current service. Possible values include always, on success, on failure, on abnormal, on abort, and on watchdog
TimeoutSec: defines the number of seconds that Systemd waits before stopping the current service
Environment: Specifies the environment variable
For a complete list of fields in the Unit configuration file, please refer to Official documents.
Dependent unit management
There are dependencies between many services. One of the highlights of systemd is that it can manage the dependencies between units. We can view the dependencies between units through the following command:
Systemctl list dependencies [unit] [– reverse], option -- reverse will track back who is using this unit.
Let's take a look at graphic Dependency of target:
[root@htlwk0001host ~]# systemctl list-dependencies multi-user.target multi-user.target ● ├─aegis.service ● ├─aliyun.service ● ├─AssistDaemon.service
The system is currently running in multi-user Under target, it has a long dependency list (only some items are intercepted above), and one of the dependent items is aliyun service. Let's use the -- reverse option to view aliyun Who uses the service unit:
[root@htlwk0001host ~]# systemctl list-dependencies --reverse aliyun.service aliyun.service ● └─multi-user.target ● └─graphical.target
As you can see above, aliyun Service is multi user Target is used, while multi-user Target is graphically Target use, in other words, multi-user Target depends on aliyun Service, while graphical Target depends on multi - user target.
List all dependencies of a Unit:
$ systemctl list-dependencies nginx.service
Some dependencies are of Target type and will not be expanded by default. If you want to expand the Target, you need to use the -- all parameter:
$ systemctl list-dependencies --all nginx.service
(5) Introduction to system D's Target
When starting the computer, you need to start a large number of units. It is obviously inconvenient to specify which units are required for each startup. System D's solution is Target.
Simply put, a Target is a Unit group that contains many related units. When a Target is started, system D will start all units in it. In this sense, the concept of Target is similar to "state point". Starting a Target is like starting to a certain state.
In the traditional init startup mode, there is the concept of Run Level, which is very similar to the function of Target. The difference is that run levels are mutually exclusive. It is impossible to start multiple run levels at the same time, but multiple targets can be started at the same time.
System D replaces the concept of System V's run level with target. In Systemd, the default run level is / etc / Systemd / system / default Target definition, the file itself is a soft connection if it points to graphical Then the default run level is the graphical interface.
Note: the Unit of target type can also be understood as the system environment. When running or switching between environments, many other units will be started to support this environment. The most common environments are character interface (multi-user.target) and graphical interface (graphical.target)
1. View all targets of the current system
[root@htlwk0001host ~]# systemctl list-unit-files --type=target UNIT FILE STATE basic.target static bluetooth.target static cloud-config.target static cloud-init.target enabled-runtime cryptsetup-pre.target static
2. View all units contained in a Target
[root@htlwk0001host ~]# systemctl list-dependencies multi-user.target
3. View the default Target at startup
[root@htlwk0001host ~]# systemctl get-default
4. Set the default Target at startup
[root@htlwk0001host ~]# sudo systemctl set-default multi-user.target
If you need to change the default target of the system to "multi-user, no graphics" mode, you can directly use ln command to connect the multi-user mode target file to the / etc/systemd/system / Directory:
[root@htlwk0001host ~]# ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target
5. Switch Target
When switching a Target, the process started by the previous Target is not closed by default,
[root@htlwk0001host ~]# systemctl isolate multi-user.target
6. Correspondence between target and traditional Run Level
Traditional runlevel New target name Symbolically linked to... Runlevel 0 | runlevel0.target -> poweroff.target Shut down the system Runlevel 1 | runlevel1.target -> rescue.target Rescue mode, single user mode Runlevel 2 | runlevel2.target -> multi-user.target Multi user, no graphic mode, character interface, standard mode, i.e. command line mode Runlevel 3 | runlevel3.target -> multi-user.target Multi user, no graphic mode, character interface, standard mode, i.e. command line mode Runlevel 4 | runlevel4.target -> multi-user.target Multi user, no graphic mode, character interface, standard mode, i.e. command line mode Runlevel 5 | runlevel5.target -> graphical.target Multi user, graphical mode Runlevel 6 | runlevel6.target -> reboot.target Restart the system
(6) System D parallel startup principle
In system D, all services are started concurrently. For example, avahi, D-Bus, livirtd, X11 and HAL can be started at the same time. At first glance, this seems to be a bit of a problem. For example, avahi needs the service of syslog. Avahi and syslog start at the same time. Assuming that avahi starts faster, so syslog is not ready, but avahi needs to record logs. Isn't this a problem?
The developers of system D carefully studied the essence of interdependence between services and found that the so-called dependency can be divided into three specific types, and each type can actually remove the dependency through corresponding technologies.
One of the principles of concurrent startup: solving socket dependency
The vast majority of service dependencies are socket dependencies. For example, service A provides its own services through A socket port S1. If other services need service A, they need to connect to S1. Therefore, if service A has not been started, S1 does not exist, and other services will get startup errors. So traditionally, people need to start service A first, wait for it to enter the ready state, and then start other services that need it. System D believes that as long as S1 is established in advance, all other services can be started at the same time without waiting for service A to create S1. If service A has not been started, the service requests sent by other processes to S1 will actually be cached by the Linux operating system, and other processes will wait at the place of this request. Once the cache service is ready, all requests can be processed immediately.
So how does the service use sockets created by the init process?
The Linux operating system has A feature that when A process calls fork or exec to create A child process, all file descriptors opened in the parent process are inherited by the child process. Socket is also A kind of file handle. Process A can create A socket. Later, when process A calls exec to start A new sub process, just ensure that the socket is closed_ on_ If the exec flag bit is cleared, the new child process can inherit the socket. The socket seen by the child process and the socket created by the parent process are the same system socket, as if the socket was created by the child process itself. There is no difference.
This feature was previously utilized by a system service called inetd. Inetd process is responsible for monitoring some common socket ports, such as telnet. Inetd starts the telnetd process only when there is a connection request on this port, and passes the connected socket to the new telnetd process for processing. In this way, when the system has no telnet client connection, there is no need to start the telnetd process. Inetd can proxy many network services, which can save a lot of system load and memory resources. Only when there is a real connection request can the corresponding service be started and the socket be passed to the corresponding service process.
Similar to inetd, systemd is the parent process of all other processes. It can first establish all required sockets, and then pass the socket to the new service process when calling exec, and the new process can directly use the socket for service.
Concurrent startup principle 2: solving D-Bus dependency
D-Bus is the abbreviation of desktop bus. It is an inter process communication mechanism with low delay, low overhead and high availability. It is increasingly used for communication between applications, as well as between applications and the operating system kernel. Many modern service processes use D-Bus instead of socket as the inter process communication mechanism to provide services. For example, the NetworkManager service that simplifies Linux network configuration uses D-Bus to interact with other applications or services: the mail client software evolution can obtain the changes of network status from the NetworkManager service through D-Bus in order to make corresponding processing.
D-Bus supports the so-called "bus activation" function. If service A needs to use the D-Bus service of service B, and service B is not running, D-Bus can automatically start service B when service A requests the D-Bus of service B. The request sent by service A will be cached by D-Bus, and service A will wait for service B to start and be ready. Using this feature, services that rely on D-Bus can be started in parallel.
Concurrent startup principle 3: solving file system dependency
During system startup, file system related activities are the most time-consuming, such as mounting the file system, performing disk check (fsck) on the file system, disk quota check and so on. While waiting for these tasks to be completed, the system is idle. Services that want to use the file system seem to have to wait for the file system initialization to complete before they can start. But systemd found that this dependency can also be avoided.
System D refers to the design idea of autofs, so that the services that depend on the file system and the initialization of the file system itself can work concurrently. Autofs can detect that a file system mount point is actually accessed before the mount operation is triggered, which is realized through the support of the kernel automounter module. For example, when an open() system call acts on "/ misc/cd/file1", the / misc/cd has not yet performed the mount operation. At this time, the open() call is suspended and waiting. The Linux kernel notifies autofs and autofs performs the mount. At this time, control is returned to the open() system call and the file is opened normally.
systemd integrates the implementation of autofs. For the mount point in the system, such as / home, when the system starts, systemd creates a temporary automatic mount point for it. At this time / home, the real mount device has not been started, the real mount operation has not been executed, and the file system detection has not been completed. However, those processes that depend on the directory can start concurrently. Their open () operation is captured by autofs built in systemd, and the open () call is suspended (interruptible sleep state). Then, after the real mount operation is completed and the file system detection is completed, systemd will replace the automatic mount point with the real mount point and let the open() call return. Thus, the services that depend on the file system and the file system itself can be started simultaneously and concurrently.
Of course, the dependency on the "/" root directory must actually be executed serially, because systemd itself is also stored under / and must wait for the system root directory to be mounted and checked.
However, for mount points such as / home, this concurrency can improve the startup speed of the system, especially when / home is a remote NFS node or encryption disk, which takes a long time to be ready. Because of concurrent startup, the system is not completely idle during this time, Instead, we can use this spare time to do more things to start the process, which in general shortens the system startup time.
(7) System D configuration usage
1. For system developers
Developers need to know more about systemd. For example, if you plan to develop a new system service, you must understand how to make this service managed by systemd. This requires your attention to the following points:
(1) The background service process code does not need to execute twice to realize the background wizard process, but only needs to realize the main loop of the service itself.
(2) Do not call setsid() and leave it to systemd.
(3) You no longer need to maintain pid files.
(4) System D provides the logging function. The service process only needs to output to stderr without using syslog.
(5) Process the signal SIGTERM. The only correct function of this signal is to stop the current service and do nothing else.
(6) The function of the SIGHUP signal is to restart the service.
(7) For services that need sockets, do not create sockets by yourself. Let systemd pass in sockets.
(8) Using SD_ The notify() function notifies the systemd service of its own state change. Generally, it can be called when the service initialization ends and enters the service ready state.
For developers, the biggest part of the workload should be to write configuration unit files to define the required units.
For example, if developers develop a new service program, such as httpd, they need to write a configuration unit file for it so that the service can be managed by systemd, similar to the working configuration file of UpStart. In this file, the command line syntax of service startup and the dependency with other services are defined.
In addition, we have learned that systemd has a wide range of functions. It can not only manage services, but also manage mount points, define scheduled tasks, etc. These tasks are completed by editing the corresponding hive file. Here are some examples of hive files.
The service hive file is displayed in Service is the suffix of the file name. The following is the configuration unit file of SSH service:
[root@htlwk0001host ~]# cat /etc/system/system/sshd.service [Unit] Description=OpenSSH server daemon [Service] EnvironmentFile=/etc/sysconfig/sshd ExecStartPre=/usr/sbin/sshd-keygen ExecStart=/usrsbin/sshd –D $OPTIONS ExecReload=/bin/kill –HUP $MAINPID KillMode=process Restart=on-failure RestartSec=42s [Install] WantedBy=multi-user.target
The document is divided into three sections:
The first part is [Unit], and there is only one description.
The second part is [Service], which defines services. ExecStartPre defines the command that should be run before starting the Service; ExecStart defines the specific command line syntax for starting the Service.
The third part is [Install]. WangtedBy indicates that this service is required in multi-user mode.
Let's take another look at multi user target:
[root@htlwk0001host ~]# cat multi-user.target [Unit] Description=Multi-User System Documentation=man.systemd.special(7) Requires=basic.target Conflicts=rescue.service rescure.target After=basic.target rescue.service rescue.target AllowIsolate=yes [Install] Alias=default.target
The requirements definition in the first part indicates multi-user When target starts, basic Target must also be started; In addition, basic When target stops, multi user Target must also stop. If you go on to look at basic Target file, you will find that it specifies sysinit Other units such as target must be started accordingly. Similarly, sysinit Target will also contain other units. The multi link structure will be adopted by users, and all services will be started in this way.
Alias is defined in the [Install] section, which defines the alias of this unit, so that this alias can be used to refer to this unit when running systemctl. The alias here is default Target, better than multi-user Target is simpler.
In addition, you can also see such as *. In the / etc/systemd/system directory The directory of wants. The configuration Unit file placed in this directory is equivalent to the wants keyword in the [Unit] section, that is, these units need to be started when this Unit is started. For example, you can simply write your own foo Put the service file into multi user target. Under the wants directory, so it will be started by default every time.
Finally, let's take a look at sys - kernel - debug Mount file, which defines a file mount point:
[root@htlwk0001host ~]# cat sys-kernel-debug.mount [Unit] Description=Debug File Syste DefaultDependencies=no ConditionPathExists=/sys/kernel/debug Before=sysinit.target [Mount] What=debugfs Where=/sys/kernel/debug Type=debugfs
This hive file defines a Mount point. The Mount configuration unit file has a [Mount] configuration section, which configures three data items: What, Where and Type. These are all necessary for the Mount command. The configuration in the example is equivalent to the following Mount command:
[root@htlwk0001host ~]# mount –t debugfs /sys/kernel/debug debugfs
The compilation of configuration unit files requires a lot of learning. You must refer to the man and other documents attached to systemd for in-depth learning. I hope that through the above small examples, you have understood the function and general writing method of configuration unit files.
2. For system administrators
As a system administrator, you must be very familiar with system services and init system management. Otherwise, please resign automatically. For example, the use of service, chkconfig and telinit commands. The Linux system using Systemd as the initialization system uses the command systemctl to manage and control the system services. There are great syntax differences between systemctl and the old commands. Therefore, as a system administrator, we must remember the differences and be able to flexibly switch between the old and new systems.
2, Use the command systemctl to manage system services
(1) Command introduction
We know that Linux distributions initialized with SysV or UpStart (for example, Linux systems before Centos 7.x under Red Hat) use the commands service and chkconfig to manage system services, while Linux distributions using system D as Init System (Linux systems after Centos 7.x) use the new management command systemctl to start Stop, restart, disable and view system services. This command integrates most of the functions of service, chkconfig, setup and init.
The systemctl command has two main functions:
- Control systemd system
- Manage services running on the system
Note: for forward compatibility, the old command service can still be used in the new version of Linux, but will be redirected to the new systemctl tool
(2) Command options
Systemctl provides a set of subcommands (command options) to manage a single unit. The command format is systemctl < command > < unit >. Unit refers to the service unit, which refers to the service process. The command options are as follows:
|start||Start the following unit immediately|
|stop||Close the following unit immediately|
|restart||Immediately close and start the unit that follows, that is, execute stop and then start|
|reload||Without closing unit, reload the configuration file to make the settings take effect|
|enable||It is set that the following unit will be started when you start the next time|
|disable||Set that the unit that follows will not be started when you start the next time|
|status||At present, the status of the following unit will list whether it is being executed, whether it is started when starting up, etc|
|is-active||Is it currently running|
|is-enable||Is this unit started by default when starting up|
|kill||Send a termination signal to the process running the unit|
|show||List the configuration of unit|
|mask||Log out of unit. After logging out, you can't start this unit|
|unmask||Cancel logout of unit|
|list-dependencies [unit] [–reverse]||Option -- reverse will track back who is using the unit|
|list-units||List all currently started services. If you add the - all option, the services that have not been started will be listed at the same time. Adding -- type can filter a certain type of unit|
|list-unit-files||List all Unios according to the files in the / lib/systemd/system / directory|
|get-default||Get the current operation mode (target)|
|set-default||Set the following target as the default operation mode|
|isolate||Switch to the following mode|
|poweroff||System shutdown, systemctl poweroff shutdown (equivalent to systemctl isolate poweroff.target)|
|reboot||Restart the system|
|suspend||Enter the pause mode, write the system data into the memory, turn off most of the hardware and wait for wake-up (equivalent to sleep under Windows)|
|hibernate||Enter sleep mode, write the system data to the hard disk, and then shut down|
|rescue||Forced entry into rescue mode|
|emergency||Forced entry into the emergency rescue mode is stronger and more thorough than the rescue mode|
(3) Comparison between Systemd command and SysV init command
|Systemd command||SysV init command||explain|
|systemctl start foo.service||service foo start||Used to start a service (does not restart the existing)|
(4) Command example
Use the option restart. If the service is running, it will restart the service; If the service is not running, it will start the service
[root@htlwk0001host ~]# systemctl restart httpd.service
2. Pure restart try restart
Use the option try restart, which will restart the service when it is already running
[root@htlwk0001host ~]# systemctl try-restart httpd.service
Using the option reload, it reloads the configuration file
[root@htlwk0001host ~]# systemctl reload httpd.service
[root@htlwk0001host ~]# systemctl start httpd.service
Out of Service
[root@htlwk0001host ~]# systemctl stop httpd.service
6. View service status
Check the status of the service. Let's see what the basic information of the service mysqld is:
[root@htlwk0001host ~]# systemctl status mysqld.service ● mysqld.service - MySQL Server Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2021-04-23 16:11:01 CST; 1 weeks 1 days ago Docs: man:mysqld(8) http://dev.mysql.com/doc/refman/en/using-systemd.html Process: 1069004 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS) Process: 1068982 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS) Main PID: 1069006 (mysqld) Tasks: 55 (limit: 23070) Memory: 344.2M CGroup: /system.slice/mysqld.service └─1069006 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid 4 June 23-16:10:59 htlwk0001host systemd: Starting MySQL Server... 4 June 23-16:11:01 htlwk0001host systemd: Started MySQL Server.
(1) Interpretation of service status information
The first line is a basic description of mysqld.
The second line describes whether the service will be started when the operating system is started. enabled means to start when the operating system is started, and disabled means not to start when the operating system is started. The configuration file path to start the service is: / usr / lib / SYSTEMd / system / mysqld service.
The third line describes the current status of the service. active (running) indicates that the service is running. If it is inactive (dead), it means that the service is not running at present. Followed by the start time of the service.
The fourth line provides the address of the online document about the service.
The seventh line shows the ID of the main process of the service.
The eighth line shows the number of tasks associated with the service.
The ninth line shows the amount of memory occupied by the service.
The last two lines are the output log information.
(2) About service startup status
For the startup status of unit, in addition to enable and disable, there are:
- static: this unit cannot be started by itself, but it may be awakened by other enabled services.
- mask: this unit cannot be started anyway! Because it has been forced to log off. You can change back to the original state through systemctl unmask.
(3) About the running state of the service
About the running status of unit, in addition to active and inactive, there are:
- active (exited): a service that normally ends after only one execution. For example, the quotaon function will only be performed once when it is powered on or mounted. This is the mode. Quotaon does not need to be executed all the time. After it is executed only once, it is handed over to the file system to handle it by itself. Most of the small services usually written in bash shell belong to this type.
- active (waiting): it is being executed, but it will wait for other events to continue processing. For example, printing related services are in this state.
7. Startup enable
Use the option enable to set the boot to start a service
[root@htlwk0001host ~]# systemctl enable httpd.service
8. Cancel startup and disable
Using the disable option to disable a service is to cancel the startup of a service
[root@htlwk0001host ~]# systemctl disable httpd.service
9. Check whether it is enabled
Check whether a service is started
[root@htlwk0001host ~]# systemctl is-enabled httpd.service
10. View the services that failed to start - failed
View services that failed to start
[root@htlwk0001host ~]# systemctl –failed
11. Check whether the process is running or is active
Check whether the process is currently running
[root@htlwk0001host ~]# systemctl is-active sshd.service
12. View all started services in the system
Entering the command systemctl is equivalent to entering systemctl list units
[root@htlwk0001host ~]# systemctl UNIT LOAD ACTIVE SUB DESCRIPTION proc-sys-fs-binfmt_misc.automount loaded active running Arbitrary Executable File Formats File System Automount Point sys-devices-pci0000:00-0000:00:03.0-virtio0-virtio\x2dports-vport0p1.device loaded active plugged /sys/devices/pci0000:00/0000:00:03.0/virtio0/virtio-ports/vport0p1 sys-devices-pci0000:00-0000:00:04.0-virtio1-block-vda-vda1.device loaded active plugged /sys/devices/pci0000:00/0000:00:04.0/virtio1/block/vda/vda1 sys-devices-pci0000:00-0000:00:04.0-virtio1-block-vda.device loaded active plugged /sys/devices/pci0000:00/0000:00:04.0/virtio1/block/vda sys-devices-pci0000:00-0000:00:05.0-virtio2-net-eth0.device loaded active plugged Virtio network device sys-devices-platform-serial8250-tty-ttyS1.device loaded active plugged /sys/devices/platform/serial8250/tty/ttyS1 sys-devices-platform-serial8250-tty-ttyS2.device loaded active plugged /sys/devices/platform/serial8250/tty/ttyS2
unit: the name of the project, including the category of each unit (see the extension).
LOAD: whether the unit configuration is loaded at startup.
active: the main running state of the service. active means "alive" and inactive means dead
SUB: the running SUB state of the service, such as running, indicates that the service is not only "alive", but also "busy"!
DESCRIPTION: DESCRIPTION information
13. View the service unit of the system according to the service file in the directory / lib/systemd/system /
[root@htlwk0001host ~]# systemctl list-unit-files; UNIT FILE STATE proc-sys-fs-binfmt_misc.automount static -.mount generated dev-hugepages.mount static dev-mqueue.mount static proc-sys-fs-binfmt_misc.mount static sys-fs-fuse-connections.mount static sys-kernel-config.mount static sys-kernel-debug.mount static tmp.mount disabled
STATE is the start STATE of the service we introduced earlier.
14. Only look at the unit of service type
[root@htlwk0001host ~]# systemctl list-units --type=service UNIT LOAD ACTIVE SUB DESCRIPTION aegis.service loaded active running LSB: aegis update. aliyun.service loaded active running Alibaba cloud assistant AssistDaemon.service loaded active running AssistDaemon atd.service loaded active running Job spooling tools auditd.service loaded active running Security Auditing Service
15. View the failed loading unit s
[root@htlwk0001host ~]# systemctl --failed 0 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'.
16. Operating environment of management system (target unit)
By specifying -- type=target, you can use the systemctl list units command to check the default number of targets in the system:
[root@htlwk0001host ~]# systemctl list-units --type=target -all UNIT LOAD ACTIVE SUB DESCRIPTION basic.target loaded active active Basic System cloud-config.target loaded active active Cloud-config availability cloud-init.target loaded active active Cloud-init target cryptsetup.target loaded active active Local Encrypted Volumes emergency.target loaded inactive dead Emergency Mode getty-pre.target loaded inactive dead Login Prompts (Pre) getty.target loaded active active Login Prompts graphical.target loaded inactive dead Graphical Interface initrd-fs.target loaded inactive dead Initrd File Systems initrd-root-device.target loaded inactive dead Initrd Root Device initrd-root-fs.target loaded inactive dead Initrd Root File System initrd-switch-root.target loaded inactive dead Switch Root initrd.target loaded inactive dead Initrd Default Target local-fs-pre.target loaded active active Local File Systems (Pre) local-fs.target loaded active active Local File Systems multi-user.target loaded active active Multi-User System network-online.target loaded active active Network is Online network-pre.target loaded active active Network (Pre) network.target loaded active active Network nss-lookup.target loaded active active Host and Network Name Lookups nss-user-lookup.target loaded active active User and Group Name Lookups paths.target loaded active active Paths remote-fs-pre.target loaded inactive dead Remote File Systems (Pre) remote-fs.target loaded active active Remote File Systems rescue.target loaded inactive dead Rescue Mode shutdown.target loaded inactive dead Shutdown slices.target loaded active active Slices sockets.target loaded active active Sockets sshd-keygen.target loaded active active sshd-keygen.target swap.target loaded active active Swap sysinit.target loaded active active System Initialization syslog.target not-found inactive dead syslog.target time-sync.target loaded inactive dead System Time Synchronized timers.target loaded active active Timers umount.target loaded inactive dead Unmount All Filesystems LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 35 loaded units listed. To show all installed unit files use 'systemctl list-unit-files'.
My server host actually has 34 targets. Here are just a few common targets:
- graphical.target: text interface plus graphical interface. This target already includes the following multi-user target
- multi-user.target: plain text mode
- rescue.target: if you can't log in with root, systemd will add an additional temporary system when starting up, which has nothing to do with your original system. At this time, you can obtain the permission of root to maintain your system
- emergency.target: an error in the emergency handling system, when rescue.com cannot be used Target, you can try this mode
- shutdown.target: execute shutdown
- getty.target: you can set the configuration of tty
The normal mode is multi - user Target and graphical There are two targets. The rescue mode is mainly rescue Target and more serious emergency target. If you want to modify the number of tty that can provide login, modify Getty target.
(1) View the current operation mode of the system (target)
[root@htlwk0001host ~]# systemctl get-default; multi-user.target
(2) Set the default operation mode of the system
[root@htlwk0001host ~]# systemctl set-default multi-user.target
(3) Switching operation mode
You can switch between different target s without restarting, such as switching from graphical interface to plain text mode (i.e. command line mode):
[root@htlwk0001host ~]# systemctl isolate multi-user.target
Switch to graphics mode:
[root@htlwk0001host ~]# systemctl isolate runlevel5.target # Operation level 5
[root@htlwk0001host ~]# systemctl isolate graphical.target
17. Put the system into pause mode
[root@htlwk0001host ~]# systemctl suspend
Pause mode saves the state of the system to memory and then shuts down most of the system hardware. Of course, it does not actually shut down. When the user presses the button to wake up the machine, the system data will be recovered from the memory, and then the hardware that is mostly closed will be driven again, so the speed of waking up the system is relatively fast.
18. Put the system into sleep mode
[root@htlwk0001host ~]# systemctl hibernate
Sleep mode is to save the system state to the hard disk. After saving, shut down the computer. When the user tries to wake up the system, the system will start normal operation, and then restore the system state saved in the hard disk. Because the data needs to be read from the hard disk, the wake-up speed is relatively slow (if you use SSD disk, the wake-up speed is also very fast).
19. Force the system to enter rescue mode
[root@htlwk0001host ~]# systemctl rescue
20. Force the system to enter the emergency rescue mode
[root@htlwk0001host ~]# systemctl emergency
22. Reload the configuration file of systemd program
[root@htlwk0001host ~]# systemctl daemon-reload
(1) When adding a new unit configuration file, you need to execute systemctl daemon reload
(2) Systemctl daemon reload also needs to be executed when the configuration file of unit changes
The daemon reload command does a lot of things. One of them is to regenerate the dependency tree (that is, the dependency relationship between units). Therefore, if you modify the dependency relationship in the unit configuration file, it will not take effect if you do not execute the daemon reload command.
23. Killing services
[root@htlwk0001host ~]# systemctl kill mysqld.service
24. Commands for managing system mount points
[root@htlwk0001host ~]# systemctl start tmp.mount
[root@htlwk0001host ~]# systemctl stop tmp.mount
[root@htlwk0001host ~]# systemctl restart tmp.mount
(4) Reload mount point
[root@htlwk0001host ~]# systemctl reload tmp.mount
(5) View mount point status
[root@htlwk0001host ~]# systemctl status tmp.mount
25. Check the version of systemd
[root@htlwk0001host ~]# systemctl --version systemd 239 +PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN2 -IDN +PCRE2 default-hierarchy=legacy
26. Check the system startup time
[root@htlwk0001host ~]# systemd-analyze Startup finished in 659ms (kernel) + 5.114s (initrd) + 10.495s (userspace) = 16.269s multi-user.target reached after 9.540s in userspace
27. Check the time spent by each process during boot
To view the startup time of each service:
[root@htlwk0001host ~]# systemd-analyze blame 5.405s cloud-init-local.service 2.875s cloud-init.service 2.631s firstname.lastname@example.org 1.707s dracut-pre-pivot.service 1.501s mysqld.service 1.095s aegis.service 954ms systemd-logind.service
28. View the key chain of the specified service
Displays the waterfall startup process flow of the specified service:
[root@htlwk0001host ~]# systemd-analyze critical-chain httpd.service The time after the unit is active or started is printed after the "@" character. The time the unit takes to start is printed after the "+" character. httpd.service +142ms └─network.target @11.168s └─network.service @9.456s +1.712s └─NetworkManager.service @8.858s +596ms └─firewalld.service @4.931s +3.926s └─basic.target @4.916s └─sockets.target @4.916s └─dbus.socket @4.916s └─sysinit.target @4.905s └─systemd-update-utmp.service @4.864s +39ms └─auditd.service @4.563s +301ms └─systemd-tmpfiles-setup.service @4.485s +69ms └─rhel-import-state.service @4.342s +142ms └─local-fs.target @4.324s └─boot.mount @4.286s +31ms └─systemd-fsck@dev-disk-by\x2duuid-79f594ad\x2da332\x2d4730\x2dbb5f\x2d85d196080964.service @4.092s +149ms └─dev-disk-by\x2duuid-79f594ad\x2da332\x2d4730\x2dbb5f\x2d85d196080964.device @4.092s
Show waterfall startup process flow:
[root@htlwk0001host ~]# systemd-analyze critical-chain
29. Get the dependency list of the service
[root@htlwk0001host ~]# systemctl list-dependencies httpd.service httpd.service ├─system.slice └─basic.target ├─firewalld.service ├─microcode.service ├─rhel-autorelabel-mark.service ├─rhel-autorelabel.service ├─rhel-configure.service ├─rhel-dmesg.service ├─rhel-loadmodules.service ├─paths.target ├─slices.target │ ├─-.slice │ └─system.slice ├─sockets.target │ ├─dbus.socket ....
30. List control groups by hierarchy
[root@htlwk0001host ~]# systemd-cgls ├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 23 ├─user.slice │ └─user-0.slice │ └─session-1.scope │ ├─2498 sshd: root@pts/0 │ ├─2500 -bash │ ├─4521 systemd-cgls │ └─4522 systemd-cgls └─system.slice ├─httpd.service │ ├─4440 /usr/sbin/httpd -DFOREGROUND │ ├─4442 /usr/sbin/httpd -DFOREGROUND │ ├─4443 /usr/sbin/httpd -DFOREGROUND │ ├─4444 /usr/sbin/httpd -DFOREGROUND │ ├─4445 /usr/sbin/httpd -DFOREGROUND │ └─4446 /usr/sbin/httpd -DFOREGROUND ├─polkit.service │ └─721 /usr/lib/polkit-1/polkitd --no-debug ....
31. List control groups according to CPU, memory, input and output
[root@htlwk0001host ~]# systemd-cgtop Path Tasks %CPU Memory Input/s Output/s / 83 1.0 437.8M - - /system.slice - 0.1 - - - /system.slice/mariadb.service 2 0.1 - - - /system.slice/tuned.service 1 0.0 - - - /system.slice/httpd.service 6 0.0 - - - /system.slice/NetworkManager.service 1 - - - - /system.slice/atop.service 1 - - - - /system.slice/atopacct.service 1 - - - - /system.slice/auditd.service 1 - - - - /system.slice/crond.service 1 - - - - /system.slice/dbus.service 1 - - - - /system.slice/firewalld.service 1 - - - - /system.slice/lvm2-lvmetad.service 1 - - - - /system.slice/polkit.service 1 - - - - /system.slice/postfix.service 3 - - - - /system.slice/rsyslog.service 1 - - - - /email@example.com 1 - - - - /system.slice/systemd-journald.service 1 - - - - /system.slice/systemd-logind.service 1 - - - - /system.slice/systemd-udevd.service 1 - - - - /system.slice/webmin.service 1 - - - - /user.slice/user-0.slice/session-1.scope 3 - - - -
32. View the unit of the specified type
[root@htlwk0001host ~]# systemctl -t target UNIT LOAD ACTIVE SUB DESCRIPTION basic.target loaded active active Basic System cloud-config.target loaded active active Cloud-config availability cloud-init.target loaded active active Cloud-init target cryptsetup.target loaded active active Local Encrypted Volumes getty.target loaded active active Login Prompts local-fs-pre.target loaded active active Local File Systems (Pre) local-fs.target loaded active active Local File Systems multi-user.target loaded active active Multi-User System network-online.target loaded active active Network is Online network-pre.target loaded active active Network (Pre) network.target loaded active active Network nss-lookup.target loaded active active Host and Network Name Lookups nss-user-lookup.target loaded active active User and Group Name Lookups paths.target loaded active active Paths remote-fs.target loaded active active Remote File Systems slices.target loaded active active Slices sockets.target loaded active active Sockets sshd-keygen.target loaded active active sshd-keygen.target swap.target loaded active active Swap sysinit.target loaded active active System Initialization timers.target loaded active active Timers LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 21 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'.
[root@htlwk0001host ~]# systemctl --type target UNIT LOAD ACTIVE SUB DESCRIPTION basic.target loaded active active Basic System cloud-config.target loaded active active Cloud-config availability cloud-init.target loaded active active Cloud-init target cryptsetup.target loaded active active Local Encrypted Volumes getty.target loaded active active Login Prompts local-fs-pre.target loaded active active Local File Systems (Pre) local-fs.target loaded active active Local File Systems multi-user.target loaded active active Multi-User System network-online.target loaded active active Network is Online network-pre.target loaded active active Network (Pre) network.target loaded active active Network nss-lookup.target loaded active active Host and Network Name Lookups nss-user-lookup.target loaded active active User and Group Name Lookups paths.target loaded active active Paths remote-fs.target loaded active active Remote File Systems slices.target loaded active active Slices sockets.target loaded active active Sockets sshd-keygen.target loaded active active sshd-keygen.target swap.target loaded active active Swap sysinit.target loaded active active System Initialization timers.target loaded active active Timers LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 21 loaded units listed. Pass --all to see loaded but inactive units
[root@htlwk0001host ~]# systemctl --type=target UNIT LOAD ACTIVE SUB DESCRIPTION basic.target loaded active active Basic System cloud-config.target loaded active active Cloud-config availability cloud-init.target loaded active active Cloud-init target cryptsetup.target loaded active active Local Encrypted Volumes getty.target loaded active active Login Prompts local-fs-pre.target loaded active active Local File Systems (Pre) local-fs.target loaded active active Local File Systems multi-user.target loaded active active Multi-User System network-online.target loaded active active Network is Online network-pre.target loaded active active Network (Pre) network.target loaded active active Network nss-lookup.target loaded active active Host and Network Name Lookups nss-user-lookup.target loaded active active User and Group Name Lookups paths.target loaded active active Paths remote-fs.target loaded active active Remote File Systems slices.target loaded active active Slices sockets.target loaded active active Sockets sshd-keygen.target loaded active active sshd-keygen.target swap.target loaded active active Swap sysinit.target loaded active active System Initialization timers.target loaded active active Timers LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 21 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'.
33. List all units that are not running
$ systemctl list-units --all --state=inactive
34. View system status
[root@htlwk0001host ~]# systemctl status ● htlwk0001host State: running Jobs: 0 queued Failed: 0 units Since: Sun 2020-08-23 18:02:02 CST; 8 months 10 days ago CGroup: / ├─user.slice │ └─user-0.slice │ ├─session-10.scope │ │ ├─ 26556 nginx: master process nginx │ │ ├─414774 nginx: worker process │ │ └─414775 nginx: worker process │ ├─session-575.scope │ │ ├─1111169 sshd: root [priv] │ │ ├─1111171 sshd: root@pts/0
35. Display the status of a Unit of the remote host
$ systemctl -H firstname.lastname@example.org status httpd.service
36. Display whether a Unit is in startup failure status
$ systemctl is-failed application.service
37. Reload all modified configuration files
$ sudo systemctl daemon-reload
38. Display the value of the specified attribute of a Unit
$ systemctl show -p CPUShares httpd.service
39. Set the specified attribute of a Unit
$ sudo systemctl set-property httpd.service CPUShares=500
(6) Comparison between systemctl and old commands
|task||Old instruction||systemctl instruction|
|Set a service to start when it is powered on||chkconfig --level 3 httpd on||systemctl enable httpd.service|
|Set a service not to start when it is started||chkconfig --level 3 httpd off||systemctl disable httpd.service|
|Check service status||service httpd status||systemctl status httpd.service|
|Show all started services||chkconfig --list||systemctl list-units --type=service|
|Start a service||service httpd start||systemctl start httpd.service|
|Stop a service||service httpd stop||systemctl stop httpd.service|
|Restart a service||service httpd restart||systemctl restart httpd.service|