编写systemd Unit文件

Uint文件语法格式参考表
在这里插入图片描述案例1
使用systemd管理shell脚本

  • 编写shell脚本

  • vim /opt/test.sh

  • #!/bin/bash

  • while :

  • do

  • echo 007

  • echo test

  • sleep 1

  • done

  • chmod +x /opt/test.sh

  • systemd Uint文件默认存储路径/usr/lib/systemd/system/

  • 拷贝crond.service 重命名为test.service

  • vim test.service

  • 在这里插入图片描述

  • /bin/kill -HUP $MAINPID //注释:不停止服务,重新加载任务

  • KillMode=process //当输入systemctl stop test时,关闭主程序

  • WantedBy=multi-user.target //支持开机自启

  • systemctl daemon-reload //刷新systemd Uint配置文件
    案例2 编写nginx的systemd Unit文件
    nginx提供网站服务时,与http类似,http服务安装后默认自带systemd Unit文件

  • 安装http,yum -y install httpd.x86_64

  • cp httpd.service nginx.service

  • 修改为ngnix启动配置

  • 在这里插入图片描述

  • After=network.target remote-fs.target nss-lookup.target

  • network.target //网络服务,开启网卡,激活ip等

  • remote-fs.target //远程的文件系统

  • nss-lookup.target //dns解析服务

  • ExecStop=/bin/kill -s QUIT ${MAINPID} //当输入systemctl stop nginx时,系统利用
    kill指令,向nginx的主程序发出退出的信号

  • ${MAINPID} //表示nginx在执行时的主进程号

  • systemctl daemon-reload //刷新systemd Uint配置文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在树莓派上编写unit文件的步骤如下: 1. 打开终端,使用sudo命令以管理员权限运行编辑器,例如: ``` sudo nano /etc/systemd/system/my-service.service ``` 2. 在编辑器中,输入以下内容: ``` [Unit] Description=My Service After=network.target [Service] ExecStart=/usr/bin/python3 /path/to/my/script.py WorkingDirectory=/path/to/my/ Restart=always User=myuser [Install] WantedBy=multi-user.target ``` 3. 解释一下这个unit文件的各个部分: - `[Unit]`:这个部分定义了服务的描述和启动顺序。 - `Description`:服务的描述。 - `After`:定义服务应该在哪些其他服务之后启动。在这个例子中,我们希望服务在网络服务启动之后启动。 - `[Service]`:这个部分定义了如何启动和运行服务。 - `ExecStart`:定义了服务启动时要运行的命令。在这个例子中,我们将用Python 3来运行一个名为script.py的脚本。 - `WorkingDirectory`:定义了服务的工作目录。 - `Restart`:定义了服务在意外停止后应该如何重启。 - `User`:定义了服务应该以哪个用户的身份运行。 - `[Install]`:这个部分定义了服务应该如何安装。 4. 编辑完成后,使用Ctrl + X,然后输入Y,再按Enter保存并退出编辑器。 5. 接下来,需要重新加载systemd配置,以便它能够识别新的unit文件。使用以下命令: ``` sudo systemctl daemon-reload ``` 6. 最后,使用以下命令启动和启用服务: ``` sudo systemctl start my-service.service sudo systemctl enable my-service.service ``` 现在,服务应该已经在后台运行了,并且在系统启动时会自动启动。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值