1.创建无挂起脚本文件
创建名为main.sh的脚本
#!/bin/sh
APP_NAME='./dist/main'
PID_RIDIAS=$(ps -ef | grep ${APP_NAME} | grep -v grep | awk '{ print $2 }')
if [ -z "$PID_RIDIAS" ]
then
echo 'Main is NOT running.'
else
echo 'Restart Main, Kill' $PID_RIDIAS
kill $PID_RIDIAS
fi
echo 'Starting Main...'
nohup ${APP_NAME} 1>/home/service/main.out 2>&1 &
PID_RIDIAS_START=$(ps -ef | grep ${APP_NAME} | grep -v grep | awk '{ print $2 }')
if [ -z "$PID_RIDIAS_START" ]
then
echo 'Main is NOT running.'
else
echo 'Main is running. Pid' $PID_RIDIAS_START
fi
其中:
./dist/main 为centos下打包好的python程序
ps -ef | grep ${APP_NAME} 查看后台所有名为APP_NAME的程序
nohup 表示不挂起的意思
1>/home/service/main.out 表示将控制台输出的message保存在main.out中
2>&1 2与>结合表示错误重定向,&与1结合表示标准输出,错误重定向到标准输出.
& 最后一个& ,表示该命令在后台执行
2.创建开机自启动脚本
1.切换到/etc/init.d目录下
cd /etc/init.d
2.制作sh脚本
vim service.sh
#!/bin/sh
#add for chkconfig
#chkconfig:2345 80 30
#description:the description of the shell
service iptables stop
su root
source /usr/local/anaconda/anaconda3/bin/activate py37
cd /home/service
./main.sh start
其中:
2345是指脚本的运行级别,即在2345这4种模式下都可以运行,234都是文本界面,5就是图形界面X
80是指脚本将来的启动顺序号,如果别的程序的启动顺序号比80小(比如44、45),则脚本需要等这些程序都启动以后才启动。
30是指系统关闭时,脚本的停止顺序号。
3.赋予权限
chmod +x service.sh
利用chkconfig命令将脚本设置为自启动:
chkconfig --add service.sh
重启计算机就生效啦!!!