本文介绍了Linux如何使用Systemd和init.d配置服务


使用Systemd配置服务

开机初始化脚本

1
nano /etc/systemd/system/rc-local.service

写入内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target

执行脚本

1
nano /etc/rc.local

写入内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
screen -dm cd /app/mcs&& screen -dm /app/jdk1.8.0_241/jre/bin/java -jar /app/mcs/1.12.2.jar nogui -Xms 4G -Xmx 4G –server
echo "看到这行字,说明添加自启动脚本成功。"
exit 0

使用脚本

1
2
3
4
chmod 755 /etc/rc.local
systemctl enable rc-local.service
systemctl start rc-local.service
systemctl status rc-local.service

使用init.d配置服务

在init.d目录下增加启动脚本

1
sudo nano /etc/init.d/aria2c 

添加脚本内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/sh

case "$1" in
start)

echo -n "已开启Aria2c"
sudo aria2c --conf-path=Aria2绝对路径aria2.conf -D
;;
stop)

echo -n "已关闭Aria2c"
killall aria2c
;;
restart)

killall aria2c
sudo aria2c --conf-path=Aria2绝对路径/aria2.conf -D
;;
esac
exit

使用脚本

1
2
3
4
5
sudo chmod 755 /etc/init.d/aria2c
sudo update-rc.d aria2c defaults
sudo service aria2c start
sudo service aria2c stop
sudo service aria2c restart