51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

CentOS7创建系统服务

概述

很多时候我们自己写了命令后,需要将其设置为后台服务运行,那么就需要创建系统服务。本文将介绍centos7下服务的创建。

CentOS7的服务systemctl脚本存放在:/usr/lib/systemd/,有系统(system)和用户(user)之分。

下面结合webify工具将pdftk封装为http服务为例,将其创建为系统服务。

webify下载地址:https://github.com/beefsack/webify/releases
pdftk安装教程:http://www.884358.com/centos-pdftk/

convert_pdf.sh内容如下:

#!/bin/bash
filename=`date +%s`
outputpath='output/'
inputpath='input/'
`result=$(wget -O ${inputpath}${filename}.pdf $1 2>&1)
if [ $? -ne 0 ];then
echo "{"code":2,"errorMsg":"download error"}"
else
result=$(pdftk ${inputpath}${filename}.pdf cat output ${outputpath}${filename}.pdf 2>&1)
if [ $? -ne 0 ];then
result=$(echo $result | sed -e 's/\n//g')
echo "{"code":1,"errorMsg":"${result}"}"
else
echo "{"code":0,"data":"${outputpath}${filename}.pdf"}"
fi
fi
`

通过/home/webify -addr=:4000 xargs /home/convert_pdf.sh即可将convert_pdf.sh运行为http服务,监听端口为4000

但是运行命令/home/webify -addr=:4000 xargs /home/convert_pdf.sh这条命令后,命令行处于执行状态,只要按ctrl+C就退出了,如何才能长期让他在后台运行?需要创建系统服务。

创建系统级服务

通常使用root账号才能创建系统级服务。

  • 创建服务文件
    新建/usr/lib/systemd/system/webify.service,内容如下:
[Unit]
Description=Webify Switchip Service
After=network.target
[Service]
Type=simple
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=/home/webify -addr=:4000 xargs /home/convert_pdf.sh
[Install]
WantedBy=multi-user.target
  • 启动服务
#添加开机启动
systemctl enable webify
#启动服务
systemctl start webify
  • 其他命令
#开机禁止启动服务
systemctl disable webify
#查看服务状态
systemctl status webify
#查看服务文件内容
systemctl cat webify

创建用户级服务 {#chuang_jian_yong_hu_ji_fu_wu}

如果你的账户不是root账户,只能以此方式进行。
用户自定义的服务可以放置在如下四个位置:
/usr/lib/systemd/user:优先级最低,会被高优先级的同名 unit 覆盖
~/.local/share/systemd/user
/etc/systemd/user:全局共享的用户级 unit[s]
~/.config/systemd/user:优先级最高

  • 创建存放服务的文件夹
mkdir -p ~/.config/systemd/user
  • 创建服务文件
vi ~/.config/systemd/user/webify.service

文件内容如下:

[Unit]
Description=Webify Switchip Service
After=network.target
[Service]
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/home/xxx/webify -addr=:4000 xargs/home/xxx/convert_pdf.sh
[Install]
WantedBy=default.target
  • 启动服务
#添加开机启动
systemctl --user enable webify
#启动服务
systemctl --user start webify
  • 其他命令
#开机禁止启动服务
systemctl --user disable webify
#查看服务状态
systemctl --user status webify
#查看服务文件内容
systemctl --user cat webify

如果中途修改过webify.service文件,需要重新加载:

systemctl --user daemon-reload

查看服务状态日志:

journalctl -f -u webify.service
赞(4)
未经允许不得转载:工具盒子 » CentOS7创建系统服务