systemd helloworld 服务实战操作.

systemd 的服务程序基础入门可以参考如下链接:

http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html
http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-part-two.html

这里是一个简单的例子(hello 级别),实战操作帮助理解上述概念

首先要有一个准备运行的后台服务程序,然后是该服务程序的配置文件,告诉systemd该如何启动这个程序。


1. 先准备一个服务程序hello.sh,用来在后台运行


$ cat /opt/hello.sh
#!/bin/bash
while true
do
    echo "hello world" >> /tmp/hello.log
    sleep 1
done
我们把hello.sh 放到了/opt 目录下,你可以随便放置到你喜欢的地方

2. 书写一个服务配置文件,让systemd知道该如何启动这个程序

这个程序按照惯例放到/etc/systemd/system 目录下:

它一般包含3个部分,Unit(单元描述),Service(服务描述),Install(安装描述)
 cat /etc/systemd/system/hello.service
 [Unit]
 Description = hello daemon

 [Service]
 ExecStart = /opt/hello.sh
 Restart = always
 Type = simple

 [Install]
 WantedBy = multi-user.target

[Unit]是单元描述信息,启动顺序,依赖关系等。
[Service]说明启动程序是什么?类型是什么? 如何启动
[Install] 说明安装到那里.

3. 实战操作


立即启动:         sudo systemctl start hello.service    #将会调用ExecStart 所指程序
立即停止:         sudo systemctl stop hello.service    #服务管理若无ExedStop, 执行默认操作
查看状态:         sudo systemctl status hello.service
查看结果:         该程序当然是看 /tmp/hello.log
加入到开机启动: sudo systemctl enable hello.service
                Created symlink from /etc/systemd/system/multi-user.target.wants/hello.service to /etc/systemd/system/hello.service.
取消开机启动:    sudo systemctl diable hello.service
                Removed symlink /etc/systemd/system/multi-user.target.wants/hello.service.

 

练习: svn 服务每次重新启动机器时都需要手动调用

/usr/bin/svnserve -d -r /home/dell1/depot

来启动,试写成服务开机启动.

答:仿照helloworld.service.

 cat svn.service
[Unit]
Description = svn daemon

[Service]
ExecStart = /usr/bin/svnserve -d -r /home/dell1/depot
Type = forking

[Install]
WantedBy = multi-user.target


只所以用forking, 因为simple 主进程会退出而成为inactive 状态,所以告诉systemd是forking.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章