参考博客:
http://blog.csdn.net/sageparadise/article/details/50622532
http://blog.csdn.net/chenxiabinffff/article/details/51374635
在参考上述博客的基础上,实现了一个简单的包含: start , stop , reload的开机自启动服务
在simple.sh中写入如下内容:
#!/bin/bash
install_path=/home/chen/script/
#安装日志,部署完成后可以查看该日志文件,从而发现部署过程中是否发生错误
log_file=$install_path"my_log.txt"
configFile=/home/chen/script/my.conf
function readConfig()
{
content=$(awk -F '=' '/content/{print $2}' $configFile)
echo $content
}
function myprint()
{
info=$1
#info=hello
while true
do
#mytime="$(date "+%Y-%m-%d %H:%M:%S")"
#result=$mytime $info
echo $(date "+%Y-%m-%d %H:%M:%S") $info|tee -a $log_file
sleep 10
done
}
function start()
{
content=$(readConfig)
myprint "$content";
}
function getPids()
{
pName=$1
pids=$(ps -ef|grep ${pName}|gawk '$0 !~/grep/ {print $2}' |tr -s '\n' ' ')
echo $pids
}
function killPids()
{
pName=$1
pids=$(getPids "$pName")
echo "killPids " $pids
kill -9 $pids
}
# stop means to find the pid related to the program , then execute kill -9
function stop()
{
pName="simple"
killPids "$pName";
}
function main()
{
if [ $# -ne 1 ];then
echo "parameter number is not 1,for example: ./install_superboard.sh start"
else
if [ "$1" == "start" ];then
start;
elif [ "$1" == "stop" ];then
stop;
elif [ "$1" == "restart" ];then
stop;
start;
else
echo "the parameter you input is false"
fi
fi
}
main $1;
在simple.service文件中写入如下内容,并将该文件移动至: /lib/systemd/system 目录下,表示作为系统服务
[Unit]
Description=my service
After=network.target
[Service]
Type=forking
PIDFile=/run/myservice.pid
ExecStart=/home/chen/script/simple.sh start
ExecReload=/home/chen/script/simple.sh restart
ExecStop=/home/chen/script/simple.sh stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
上述参数的意思是(参考自:http://blog.csdn.net/sageparadise/article/details/50622532):
[Unit]:服务的说明
Description:描述服务
After:描述服务类别
[Service]服务运行参数的设置
Type=forking是后台运行的形式
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
[Install]服务安装的相关设置,可设置为多用户 Linux学习,http:// linux.it.NET.cn
2.保存目录
以754的权限保存在目录:/lib/systemd/system
3.设置开机自启动
systemctl enable simple.service
启动服务
systemctl start simple
禁用服务
systemctl disable simple.service