linux systemd 从简单的例子入门
linux systemd 从简单的例子入门
网上很多相关链接,一上来就给一大堆命令和讲解,让人头都大。
我们希望有一个service(服务),让它在开机启动的时候就执行。
用 root 登陆以后:
新建service
vim /etc/systemd/system/my-test-daemon.service
输入以下内容(有看过文章说=号前后不要有空格,有空格可不可以没测试过)按 i 键进入编辑模式:
[Unit]
Description=my test daemon
[Service]
ExecStart=/usr/bin/git daemon --verbose --export-all --base-path=/var/lib/git /var/lib/git
Restart=always
Type=simple
[Install]
WantedBy=multi-user.target
esc->:wq 保存退出
例子中我用了 git daem,git daemon 需要安装的话,在 Centos 系统中的命令是 yum install -y git-deamon,不同系统有不同的安装方式。
注意:ExecStart=后面的命令要给一个绝对路径,不能只写命令,ExecStart=git daemon --verbose --export-all --base-path=/var/lib/git /var/lib/git 这样会运行不成功
查看是否建立成功
systemctl list-unit-files --type=service | grep my-test-daemon
显示输出:
my-test-daemon.service disabled
可以看出目前是关闭状态
设置开机启动
systemctl enable my-test-daemon
显示输出:
Created symlink /etc/systemd/system/multi-user.target.wants/my-test-daemon.service -> /etc/systemd/system/my-test-daemon.service
可以看出,开启就是在 /etc/systemd/system/multi-user.target.wants/ 中创建了一个相应的链接,创建的位置应该就是跟 [Install] 中的 WantedBy 有关
当前启动
因为我们上面只是新建了一个service和设置了开机启动,只有以后开机后才会自动启动,如果我们现在不想重启就想启动:
systemctl start my-test-daemon
查看service状态
systemctl status my-test-daemon
重启系统
reboot
然后登陆在看看serveice的状态,确认开机是否自动启动
去除开机启动
systemctl disable my-test-daemon
显示输出:
Removed /etc/systemd/system/multi-user.target.wants/my-test-daemon.service.
以上是一个简单的例子,可以满足很基本的需求,更加复杂的需求就可以搜 systemd 了