https://blog.csdn.net/qq_33319299/article/details/103220670?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
ubuntu-18.04 LTS版本改用了systemd
来管理系统服务
systemd 默认从目录 /etc/systemd/system/
读取配置文件。但是,里面存放的大部分文件都是符号链接,指向目录 /lib/systemd/system/
,真正的配置文件存放在这个目录。
一般系统管理员手工创建的单元文件建议存放在 /etc/systemd/system/
目录下面。
接下来开始设置开机自启
vi /etc/demo.local
#!/bin/bash -e echo success>/tmp/success
chmod 755 /etc/demo.local
-e
的意思是某一句出错继续往下执行而不会停止,这里我们在/tmp/目录下创建个success文件来看是否成功
/etc/systemd/system/
目录下创建一个demo.service文件,内容如下:注意:此处的文件名后缀必须为 .service
,因为它指定了该 Unit 的种类,其他常见的 Unit 种类请阅读最下面的推荐阅读。
[Unit] Description=demo daemon ConditionFileIsExecutable=/etc/demo.local # 检测指定的路径是否存在并且是一个可执行文件,必须使用绝对路径 After=network.target [Service] Type=forking # 各启动类型区别 https://superuser.com/questions/1274901/systemd-forking-vs-simple/1274913 ExecStart=/etc/demo.local # 定义启动进程时执行的命令(重要) TimeoutSec=10 # 关机时显示的 A stop job is running for xxx (*s / 10s) 中的10 Restart=always User=ctf # 设置执行进程的UNIX用户 #Group=ctf # 设置执行进程的UNIX组 [Install] WantedBy=multi-user.target # Target的含义是服务组,表示一组服务。 # WantedBy=multi-user.target指的是,demo所在的 Target 是multi-user.target。 # 这个设置非常重要,因为执行systemctl enable demo.service命令时, # sshd.service的一个符号链接,就会放在/etc/systemd/system目录下面的multi-user.target.wants子目录之中。
注意以上的 /etc/demo.local
替换成你自己启动脚本所在位置
[Unit] 段: 启动顺序与依赖关系
[Service] 段: 启动行为,如何启动,启动类型
[Install] 段: 定义如何安装这个配置文件,即怎样做到开机启动
各字段详细信息可以参考以下地址:
http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html
执行 sudo systemctl enable demo.service
,(systemctl enable /opt/SVN/svn_njhy.service)命令用于建立符号链接关系,相当于激活开机启动
sudo systemctl enable demo
省略后缀,因为systemd 默认后缀名为 .service
,所以 demo 会被理解成 demo.service
。sudo ln -s '/etc/systemd/system/demo.service' '/etc/systemd/system/multi-user.target.wants/demo.service'
/etc/systemd/system/multi-user.target.wants
看一下,可以看到第二列硬链接的个数是 1
,所以是一个指向 /etc/systemd/system/demo.service
的符号连接。重启后就可以看到 /tmp/ 目录下已经创建了 success
文件
其他常用命令:
systemctl status demo.service
查看该 Unit 运行状态systemctl disable demo.service
命令用于在两个目录之间,撤销符号链接关系,相当于撤销开机启动。systemctl is-enabled demo.service
可显示某个 Unit 服务是否建立了启动链接。systemctl show demo.service
可显示该 Unit 的所有底层参数。
systemctl disable demo.service
命令用于在两个目录之间,撤销符号链接关系,相当于撤销开机启动。systemctl is-enabled demo.service
可显示某个 Unit 服务是否建立了启动链接。systemctl show demo.service
可显示该 Unit 的所有底层参数。systemctl cat demo.service
查看配置文件内容
联系客服