红联Linux门户
Linux帮助

在Linux中将脚本做成系统服务

发布时间:2016-11-18 11:22:27来源:linux网站作者:郭延龙
有一些情况下,我们需要将某些脚本作为系统服务来运行。比如,在我使用workerman框架开发php程序时,需要使用管理员权限来运行,而且需要开机自行启动程序提供服务。这个时候将启动程序写成服务就可以很方便使用了,而且在使用时也可以直接sudo service xxxx start,不需要手动敲出来复杂的文件路径。(在不使用小技巧的时候可能要这样做: sudo php /path/to/file start -d)生命苦短,多用些小技巧可能提高我们生命的效率。我们直接来看如何自己写一个,并将之作为系统服务,且开机自动运行。
 
首先,作为服务我们通常需要以下的功能:{start|stop|restart|status},接下来我就使用一段简单的bash脚本做一个演示:
 
编辑我们的脚本文件
vim myservice
 
脚本内容:
#!/bin/bash
#
#description: a demo
#chkconfig:2345 88 77
lockfile=/var/lock/subsys/myservice
touch $lockfile
# start
start(){
if [ -e $lockfile ] ;then
echo "Service is already running....."
return 5
else
touch $lockfile
echo "Service start ..."
return 0
fi
}
#stop
stop(){
if [ -e $lockfile ] ; then
rm -f $lockfile
echo "Service is stoped "
return 0
else
echo "Service is not run "
return 5
fi
}
#restart
restart(){
stop
start
}
usage(){
echo "Usage:{start|stop|restart|status}"
}
status(){
if [ -e $lockfile ];then
echo "Service is running .."
return 0
else
echo "Service is stop "
return 0
fi
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
*)
usage
exit 7
;;
esac
 
之后,我们将脚本复制至/etc/init.d文件夹中
#cp myservice /etc/init.d
将我们的myservice.sh添加至chkconfig
#chkcofig --add myservice
这样,在2345的运行级别下,myservice就会开机自动开启服务了,我们在任意目录下面都可以直接运行脚本 service myservice start
 
本文永久更新地址:http://www.linuxdiyf.com/linux/26104.html