Linux:添加系统服务并设置为开机自启

添加一个自启服务

1. 用自带的 /etc/rc.local脚本

执行命令: 编辑”/etc/rc.local”,添加你想开机运行的命令

运行程序脚本: 然后在文件最后一行添加要执行程序的全路径。

例如,每次开机时要执行一个io这个程序,这个脚本放在/root/io_test下面,那就可以在”/etc/rc.local”中加一行cd /root/io_test/ && ./io,或者/root/io_test/ ./io

img.png

注意,你的命令应该添加在:exit 0 之前!

它是怎么执行的呢?

/lib/systemd/system/目录,找到rc.local.service文件,打开看看。

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

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

看这个 ExecStart=/etc/rc.local start,明白了吧。

还不懂的请查看这边博文 Systemd 入门教程:命令篇

2. 新建一个自己的

不想努力了 😂