實踐:
1)
vim /lib/systemd/system/WebSvc.service
[Unit]
Description=WebSvc service
[Service]
Type=forking
RemainAfterExit=no
ExecStart=/bin/sh /home/testWebSvc/systemctWebSvc.sh
[Install]
WantedBy=multi-user.target
CMD
systemctl enable WebSvc;
Created symlink from /etc/systemd/system/multi-user.target.wants/WebSvc.service to /lib/systemd/system/WebSvc.service.
#!/bin/bash
sleep 1s
/usr/bin/nohup /home/test/WebSvc -conf /home/test/WebSvc/configs/config.yaml > /dev/null 2>&1 &
systemctl --help
systemctl [OPTIONS...] {COMMAND} ...
Query or send control commands to the systemd manager.
-h --help Show this help
--version Show package version
--system Connect to system manager
--user Connect to user service manager
-H --host=[USER@]HOST
Operate on remote host
-M --machine=CONTAINER
Operate on local container
-t --type=TYPE List units of a particular type
--state=STATE List units with particular LOAD or SUB or ACTIVE state
-p --property=NAME Show only properties by this name
-a --all Show all loaded units/properties, including dead/empty
ones. To list all units installed on the system, use
the 'list-unit-files' command instead.
-l --full Don't ellipsize unit names on output
-r --recursive Show unit list of host and local containers
--reverse Show reverse dependencies with 'list-dependencies'
--job-mode=MODE Specify how to deal with already queued jobs, when
queueing a new job
--show-types When showing sockets, explicitly show their type
-i --ignore-inhibitors
When shutting down or sleeping, ignore inhibitors
--kill-who=WHO Who to send signal to
-s --signal=SIGNAL Which signal to send
--now Start or stop unit in addition to enabling or disabling it
-q --quiet Suppress output
--no-block Do not wait until operation finished
--no-wall Don't send wall message before halt/power-off/reboot
--no-reload Don't reload daemon after en-/dis-abling unit files
--no-legend Do not print a legend (column headers and hints)
--no-pager Do not pipe output into a pager
--no-ask-password
Do not ask for system passwords
--global Enable/disable unit files globally
--runtime Enable unit files only temporarily until next reboot
-f --force When enabling unit files, override existing symlinks
When shutting down, execute action immediately
--preset-mode= Apply only enable, only disable, or all presets
--root=PATH Enable unit files in the specified root directory
-n --lines=INTEGER Number of journal entries to show
-o --output=STRING Change journal output mode (short, short-iso,
short-precise, short-monotonic, verbose,
export, json, json-pretty, json-sse, cat)
--firmware-setup Tell the firmware to show the setup menu on next boot
--plain Print unit dependencies as a list instead of a tree
lines 27-49
--kill-who=WHO Who to send signal to
-s --signal=SIGNAL Which signal to send
--now Start or stop unit in addition to enabling or disabling it
-q --quiet Suppress output
--no-block Do not wait until operation finished
--no-wall Don't send wall message before halt/power-off/reboot
--no-reload Don't reload daemon after en-/dis-abling unit files
--no-legend Do not print a legend (column headers and hints)
--no-pager Do not pipe output into a pager
--no-ask-password
Do not ask for system passwords
--global Enable/disable unit files globally
--runtime Enable unit files only temporarily until next reboot
-f --force When enabling unit files, override existing symlinks
When shutting down, execute action immediately
--preset-mode= Apply only enable, only disable, or all presets
--root=PATH Enable unit files in the specified root directory
-n --lines=INTEGER Number of journal entries to show
-o --output=STRING Change journal output mode (short, short-iso,
short-precise, short-monotonic, verbose,
export, json, json-pretty, json-sse, cat)
--firmware-setup Tell the firmware to show the setup menu on next boot
--plain Print unit dependencies as a list instead of a tree
Unit Commands:
list-units [PATTERN...] List loaded units
list-sockets [PATTERN...] List loaded sockets ordered by address
list-timers [PATTERN...] List loaded timers ordered by next elapse
start NAME... Start (activate) one or more units
stop NAME... Stop (deactivate) one or more units
reload NAME... Reload one or more units
restart NAME... Start or restart one or more units
try-restart NAME... Restart one or more units if active
reload-or-restart NAME... Reload one or more units if possible,
otherwise start or restart
try-reload-or-restart NAME... If active, reload one or more units,
if supported, otherwise restart
isolate NAME Start one unit and stop all others
kill NAME... Send signal to processes of a unit
is-active PATTERN... Check whether units are active
is-failed PATTERN... Check whether units are failed
status [PATTERN...|PID...] Show runtime status of one or more units
show [PATTERN...|JOB...] Show properties of one or more
units/jobs or the manager
cat PATTERN... Show files and drop-ins of one or more units
set-property NAME ASSIGNMENT... Sets one or more properties of a unit
help PATTERN...|PID... Show manual for one or more units
reset-failed [PATTERN...] Reset failed state for all, one, or more
units
list-dependencies [NAME] Recursively show units which are required
or wanted by this unit or by which this
unit is required or wanted
Unit File Commands:
list-unit-files [PATTERN...] List installed unit files
enable NAME... Enable one or more unit files
disable NAME... Disable one or more unit files
reenable NAME... Reenable one or more unit files
preset NAME... Enable/disable one or more unit files
based on preset configuration
preset-all Enable/disable all unit files based on
preset configuration
is-enabled NAME... Check whether unit files are enabled
mask NAME... Mask one or more units
unmask NAME... Unmask one or more units
link PATH... Link one or more units files into
the search path
add-wants TARGET NAME... Add 'Wants' dependency for the target
on specified one or more units
add-requires TARGET NAME... Add 'Requires' dependency for the target
on specified one or more units
edit NAME... Edit one or more unit files
get-default Get the name of the default target
set-default NAME Set the default target
Machine Commands:
list-machines [PATTERN...] List local containers and host
Job Commands:
list-jobs [PATTERN...] List jobs
cancel [JOB...] Cancel all, one, or more jobs
Environment Commands:
show-environment Dump environment
set-environment NAME=VALUE... Set one or more environment variables
unset-environment NAME... Unset one or more environment variables
import-environment [NAME...] Import all or some environment variables
Manager Lifecycle Commands:
daemon-reload Reload systemd manager configuration
daemon-reexec Reexecute systemd manager
System Commands:
is-system-running Check whether system is fully running
default Enter system default mode
rescue Enter system rescue mode
emergency Enter system emergency mode
halt Shut down and halt the system
poweroff Shut down and power-off the system
reboot [ARG] Shut down and reboot the system
kexec Shut down and reboot the system with kexec
exit [EXIT_CODE] Request user instance or container exit
switch-root ROOT [INIT] Change to a different root file system
suspend Suspend the system
hibernate Hibernate the system
hybrid-sleep Hibernate and suspend the system
lines 91-132/132 (END)
systemctl開機啟動設置_龍哥哥的博客-CSDN博客_systemctl 開機啟動 https://blog.csdn.net/tl4832194/article/details/109781230
常用的systemctl命令
以sshd服務為例,列出常用systemctl命令:
啟動sshd服務:systemctl start ssh.service
停止sshd服務:systemctl stop ssh.service
查看sshd服務狀態:systemctl status ssh.service
重啟sshd服務:systemctl restart ssh.service
設置開機自啟動:systemctl enable ssh.service
禁止開機自啟動:systemctl disable ssh.service
查看所有已經啟動的服務:systemctl list-units --type=service
重新加載配置文件:systemctl daemon-reload
systemctl啟動服務編寫
Centos7的服務systemctl腳本存放在:/usr/lib/systemd/目錄下,有系統(system)和用戶(user)之分,一般需要開機不登錄就能運行的程序,就存放在/usr/lib/systemd/system/目錄下
每一個服務以.service結尾,一般會分為3部分:[Unit]、[Service]和[Install],以sshd為實例如下:
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.service
Wants=sshd-keygen.service
[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
[Unit]部分主要是對這個服務的說明,內容包括Description和After,Description 用於描述服務,After用於描述服務類別;
[Service]部分是服務的關鍵,是服務的一些具體運行參數的設置;
[Install]部分是服務安裝的相關設置,可設置為多用戶的;
配置文件詳解
Unit
After 表示服務需要在***服務啟動之后執行 無依賴
Before 表示服務需要在***服務啟動之前執行 無依賴
Wants 弱依賴關系
Requires 強依賴關系 ***停止之后本服務也必須停止
Service
ExecStart 啟動進程時執行的命令
ExecReload 重啟服務時執行的命令
ExecStop 停止服務時執行的命令
ExecStartPre 啟動服務之前執行的命令
ExecStartPost 啟動服務之后執行的命令
ExecStopPost 停止服務之后執行的命令
所有的啟動設置之前,都可以加上一個 連詞號(-),表示"抑制錯誤", 即發生錯誤的時候,不影響其他命令的執行。比如,EnvironmentFile=-/etc/sysconfig/sshd(注意等號后面的那個連詞號),就表示即使/etc/sysconfig/sshd文件不存在,也不會拋出錯誤。
type參數說明
simple(默認值) ExecStart字段啟動的進程為主進程
forking ExecStart字段將以fork()方式啟動,此時父進程將會退出,子進程將成為主進程
oneshot 類似於simple,但只執行一次,Systemd 會等它執行完,才啟動其他服務
dbus 類似於simple,但會等待 D-Bus 信號后啟動
notify 類似於simple,啟動結束后會發出通知信號,然后 Systemd 再啟動其他服務
idle 類似於simple,但是要等到其他任務都執行完,才會啟動該服務。一種使用場合是為讓該服務的輸出,不與其他服務的輸出相混合
KillMode參數說明
control-group(默認值) 當前控制組里面的所有子進程,都會被殺掉
process 只殺主進程
mixed 主進程將收到 SIGTERM 信號,子進程收到 SIGKILL 信號
none 沒有進程會被殺掉,只是執行服務的 stop 命令。
Restart參數說明
no(默認值) 退出后不會重啟
on-success 只有正常退出時(退出狀態碼為0),才會重啟
on-failure 非正常退出時(退出狀態碼非0),包括被信號終止和超時,才會重啟
on-abnormal 只有被信號終止和超時,才會重啟
on-abort 只有在收到沒有捕捉到的信號終止時,才會重啟
on-watchdog 超時退出,才會重啟
always 不管是什么退出原因,總是重啟
修改配置文件以后,需要重新加載配置文件,然后重新啟動相關服務。
重新加載配置文件
systemctl daemon-reload
1
Linux 服務管理兩種方式service和systemctl - 迪米特 - 博客園 https://www.cnblogs.com/shijingjing07/p/9301590.html
Linux 服務管理兩種方式service和systemctl
1.service命令
service命令其實是去/etc/init.d目錄下,去執行相關程序
# service命令啟動redis腳本 service redis start # 直接啟動redis腳本 /etc/init.d/redis start # 開機自啟動 update-rc.d redis defaults
其中腳本需要我們自己編寫
2.systemctl命令
systemd是Linux系統最新的初始化系統(init),作用是提高系統的啟動速度,盡可能啟動較少的進程,盡可能更多進程並發啟動。
systemd對應的進程管理命令是systemctl
1)systemctl命令兼容了service
即systemctl也會去/etc/init.d目錄下,查看,執行相關程序
systemctl redis start systemctl redis stop # 開機自啟動 systemctl enable redis
2)systemctl命令管理systemd的資源Unit
systemd的Unit放在目錄/usr/lib/systemd/system(Centos)或/etc/systemd/system(Ubuntu)
主要有四種類型文件.mount,.service,.target,.wants
.mount文件
.mount文件定義了一個掛載點,[Mount]節點里配置了What,Where,Type三個數據項
等同於以下命令:
mount -t hugetlbfs /dev/hugepages hugetlbfs
.service文件
.service文件定義了一個服務,分為[Unit],[Service],[Install]三個小節
[Unit]
Description:描述,
After:在network.target,auditd.service啟動后才啟動
ConditionPathExists: 執行條件
[Service]
EnvironmentFile:變量所在文件
ExecStart: 執行啟動腳本
Restart: fail時重啟
[Install]
Alias:服務別名
WangtedBy: 多用戶模式下需要的
.target文件
.target定義了一些基礎的組件,供.service文件調用
.wants文件
.wants文件定義了要執行的文件集合,每次執行,.wants文件夾里面的文件都會執行
Web進程的服務化
cd /lib/systemd/system;
vim WebSvc.service
[Unit]
Description=WebSvc service
[Service]
Type=forking
RemainAfterExit=no
ExecStart=/bin/sh /home/test/WebSvc/LinuxWebSvc.sh
[Install]
WantedBy=multi-user.target
開機啟動
systemctl enable WebSvc
sudo systemctl daemon-reload;sudo systemctl start WebSvc;
sudo systemctl daemon-reload;sudo systemctl restart WebSvc;
sudo systemctl status WebSvc.service;
sudo systemctl stop WebSvc;
cat LinuxWebSvc.sh
sleep 8s # TODO 等待啟動依賴的程序啟動
/usr/bin/nohup /home/test/WebSvc -conf /home/test/configs/config.yaml > /dev/null&
Linux使用systemctl設置程序開機自啟動_sayyy的專欄-CSDN博客_systemctl 開機自啟動 https://blog.csdn.net/sayyy/article/details/79276575
/etc/init.d$ cat mysql
# Start MySQL!
su - mysql -s /bin/sh -c "/usr/bin/mysqld_safe > /dev/null 2>&1 &"
/etc/init.d$ cat mysql
#!/bin/bash
#
### BEGIN INIT INFO
# Provides: mysql
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: $network $time
# Should-Stop: $network $time
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop the mysql database server daemon
# Description: Controls the main MySQL database server daemon "mysqld"
# and its wrapper script "mysqld_safe".
### END INIT INFO
#
set -e
set -u
${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
test -x /usr/bin/mysqld_safe || exit 0
. /lib/lsb/init-functions
SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
CONF=/etc/mysql/my.cnf
MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
# priority can be overriden and "-s" adds output to stderr
ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mysql -i"
# Safeguard (relative paths, core dumps..)
cd /
umask 077
# mysqladmin likes to read /root/.my.cnf. This is usually not what I want
# as many admins e.g. only store a password without a username there and
# so break my scripts.
export HOME=/etc/mysql/
## Fetch a particular option from mysql's invocation.
#
# Usage: void mysqld_get_param option
mysqld_get_param() {
/usr/sbin/mysqld --print-defaults \
| tr " " "\n" \
| grep -- "--$1" \
| tail -n 1 \
| cut -d= -f2
}
## Do some sanity checks before even trying to start mysqld.
sanity_checks() {
# check for config file
if [ ! -r /etc/mysql/my.cnf ]; then
log_warning_msg "$0: WARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz"
echo "WARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz" | $ERR_LOGGER
fi
# check for diskspace shortage
datadir=`mysqld_get_param datadir`
if LC_ALL=C BLOCKSIZE= df --portability $datadir/. | tail -n 1 | awk '{ exit ($4>4096) }'; then
log_failure_msg "$0: ERROR: The partition with $datadir is too full!"
echo "ERROR: The partition with $datadir is too full!" | $ERR_LOGGER
exit 1
fi
}
## Checks if there is a server running and if so if it is accessible.
#
# check_alive insists on a pingable server
# check_dead also fails if there is a lost mysqld in the process list
#
# Usage: boolean mysqld_status [check_alive|check_dead] [warn|nowarn]
mysqld_status () {
ping_output=`$MYADMIN ping 2>&1`; ping_alive=$(( ! $? ))
ps_alive=0
pidfile=`mysqld_get_param pid-file`
if [ -f "$pidfile" ] && ps `cat $pidfile` >/dev/null 2>&1; then ps_alive=1; fi
if [ "$1" = "check_alive" -a $ping_alive = 1 ] ||
[ "$1" = "check_dead" -a $ping_alive = 0 -a $ps_alive = 0 ]; then
return 0 # EXIT_SUCCESS
else
if [ "$2" = "warn" ]; then
echo -e "$ps_alive processes alive and '$MYADMIN ping' resulted in\n$ping_output\n" | $ERR_LOGGER -p daemon.debug
fi
return 1 # EXIT_FAILURE
fi
}
#
# main()
#
case "${1:-''}" in
'start')
sanity_checks;
# Start daemon
log_daemon_msg "Starting MySQL database server" "mysqld"
if mysqld_status check_alive nowarn; then
log_progress_msg "already running"
log_end_msg 0
else
# Could be removed during boot
test -e /var/run/mysqld || install -m 755 -o mysql -g root -d /var/run/mysqld
# Start MySQL!
su - mysql -s /bin/sh -c "/usr/bin/mysqld_safe > /dev/null 2>&1 &"
# 6s was reported in #352070 to be too few when using ndbcluster
# 14s was reported in #736452 to be too few with large installs
for i in $(seq 1 30); do
sleep 1
if mysqld_status check_alive nowarn ; then break; fi
log_progress_msg "."
done
if mysqld_status check_alive warn; then
log_end_msg 0
# Now start mysqlcheck or whatever the admin wants.
output=$(/etc/mysql/debian-start)
[ -n "$output" ] && log_action_msg "$output"
else
log_end_msg 1
log_failure_msg "Please take a look at the syslog"
fi
fi
;;
'stop')
# * As a passwordless mysqladmin (e.g. via ~/.my.cnf) must be possible
# at least for cron, we can rely on it here, too. (although we have
# to specify it explicit as e.g. sudo environments points to the normal
# users home and not /root)
log_daemon_msg "Stopping MySQL database server" "mysqld"
if ! mysqld_status check_dead nowarn; then
set +e
shutdown_out=`$MYADMIN shutdown 2>&1`; r=$?
set -e
if [ "$r" -ne 0 ]; then
log_end_msg 1
[ "$VERBOSE" != "no" ] && log_failure_msg "Error: $shutdown_out"
log_daemon_msg "Killing MySQL database server by signal" "mysqld"
killall -15 mysqld
server_down=
for i in 1 2 3 4 5 6 7 8 9 10; do
sleep 1
if mysqld_status check_dead nowarn; then server_down=1; break; fi
done
if test -z "$server_down"; then killall -9 mysqld; fi
fi
fi
if ! mysqld_status check_dead warn; then
log_end_msg 1
log_failure_msg "Please stop MySQL manually and read /usr/share/doc/mysql-server-5.7/README.Debian.gz!"
exit -1
else
log_end_msg 0
fi
;;
'restart')
set +e; $SELF stop; set -e
$SELF start
;;
'reload'|'force-reload')
log_daemon_msg "Reloading MySQL database server" "mysqld"
$MYADMIN reload
log_end_msg 0
;;
'status')
if mysqld_status check_alive nowarn; then
log_action_msg "$($MYADMIN version)"
else
log_action_msg "MySQL is stopped."
exit 3
fi
;;
*)
echo "Usage: $SELF start|stop|restart|reload|force-reload|status"
exit 1
;;
esac
# Some success paths end up returning non-zero so exit 0 explicitly. See
# bug #739846.
exit 0
