进程启停脚本模板

2021/7/30 7:38:06

本文主要是介绍进程启停脚本模板,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录

  • 启动脚本
  • 停止脚本

在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修改为对应名称即可。



这篇关于进程启停脚本模板的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程