系统相关
首页 > 系统相关> > 进程启停脚本模板

进程启停脚本模板

作者:互联网

目录

在Linux上启动程序后台运行时,往往需要输入一堆复杂的命令,为了能快速编写一个完善的启动脚本,整理一个通用的启停脚本模板如下。
脚本支持从任意位置执行,不存在路径问题。

启动脚本

#!/bin/bash

current_path=$(cd `dirname $0`; pwd)
parent_path=$(cd ${current_path} ; cd ..; pwd)
#echo $current_path
#echo $parent_path

pid_file=$current_path/xxx.pid
arg1=$1
arg2=$2

function print_usage() {
    echo ""
    echo "Usage:"
    echo "    sh $0 <arg1> <arg2>"
    echo ""
    echo "  e.g:"
    echo "    sh $0 yyy zzz"
    echo ""
}

if [ ! "${arg1}" ]; then
    print_usage
    exit 1
fi

if [ ! "${arg2}" ]; then
    print_usage
    exit 1
fi

#print_usage

if [ -f ${pid_file} ]; then
    pid=`cat ${pid_file}`
    pid_exist=$(ps aux | awk '{print $2}'| grep -w $pid)
    if [ $pid_exist ]; then
        echo ""
        echo "process is running: ${pid}, Please stop it first!"
        echo ""
        exit 1
    fi
fi

echo "startup..."
echo "arg1: ${arg1}, arg2: ${arg2}"

# start python process
#nohup python ${parent_path}/test_tasks.py -s ${arg1} -c ${arg2} -pf prod --useproxy > /dev/null 2>&1 & echo $! > $pid_file

# start java process
# TODO

sleep 1
echo "started."
echo "process id: `cat ${pid_file}`"
echo ""

根据实际情况,将脚本模板中的xxxarg1arg2修改为对应的名称即可。

停止脚本

#!/bin/bash

current_path=$(cd `dirname $0`; pwd)
#echo $current_path

pid_file=$current_path/xxx.pid

if [ ! -f $pid_file ]; then
    echo "pid file not exists"
    echo ""
    exit 1
fi

echo "stopping..."
pid=`cat ${pid_file}`
echo "process id: ${pid}"
kill -15 $pid
sleep 1

# check process exists
pid_exist=$(ps aux | awk '{print $2}'| grep -w $pid)
if [ ! $pid_exist ]; then
    # echo the process $pid is not exist
    rm -rf ${pid_file}
else
    # echo the process $pid exist
    kill -9 $pid
    sleep 1
    rm -rf ${pid_file}
fi

echo "stopped."

根据实际情况,将脚本模板中xxx修改为对应名称即可。

标签:脚本,process,pid,echo,current,启停,file,path,模板
来源: https://www.cnblogs.com/nuccch/p/15076912.html