fix: kill process by pid

This commit is contained in:
zhuyasen 2025-04-17 19:47:10 +08:00
parent abac2bbf82
commit fa5e1921ce
1 changed files with 35 additions and 19 deletions

View File

@ -5,6 +5,7 @@
serverName="serverNameExample_mixExample"
cmdStr="cmd/${serverName}/${serverName}"
pidFile="cmd/${serverName}/${serverName}.pid"
configFile=$1
function checkResult() {
@ -14,43 +15,58 @@ function checkResult() {
fi
}
stopService(){
NAME=$1
function stopService(){
local NAME=$1
ID=`ps -ef | grep "$NAME" | grep -v "$0" | grep -v "grep" | awk '{print $2}'`
# priority to kill process by pid
if [ -f "${pidFile}" ]; then
local pid=$(cat "${pidFile}")
local processInfo=`ps -p "${pid}" | grep "${cmdStr}"`
if [ -n "${processInfo}" ]; then
kill -9 ${pid}
checkResult $?
echo "Stopped ${NAME} service successfully, process ID=${pid}"
rm -f ${pidFile}
return 0
fi
fi
# if the pid file does not exist, get the pid from the process name and kill the process
ID=`ps -ef | grep "${cmdStr}" | grep -v "$0" | grep -v "grep" | awk '{print $2}'`
if [ -n "$ID" ]; then
for id in $ID
do
kill -9 $id
echo "Stopped ${NAME} service successfully, process ID=${ID}"
return 0
done
fi
}
startService() {
NAME=$1
function startService() {
local NAME=$1
if [ -f "${NAME}" ] ;then
rm "${NAME}"
fi
sleep 0.2
go build -o ${cmdStr} cmd/${NAME}/main.go
checkResult $?
# running server
# running server, append log to file
if test -f "$configFile"; then
echo "Using config file: $configFile"
nohup ${cmdStr} -c $configFile > ${NAME}.log 2>&1 &
nohup ${cmdStr} -c $configFile >> ${NAME}.log 2>&1 &
else
nohup ${cmdStr} > ${NAME}.log 2>&1 &
nohup ${cmdStr} >> ${NAME}.log 2>&1 &
fi
local pid=$!
printf "%s" "${pid}" > "${pidFile}"
sleep 1
ID=`ps -ef | grep "$NAME" | grep -v "$0" | grep -v "grep" | awk '{print $2}'`
if [ -n "$ID" ]; then
echo "Start the ${NAME} service successfully, process ID=${ID}"
local processInfo=`ps -p "${pid}" | grep "${cmdStr}"`
if [ -n "${processInfo}" ]; then
echo "Started the ${NAME} service successfully, process ID=${pid}"
else
echo "Failed to start ${NAME} service"
rm -f ${pidFile}
return 1
fi
return 0
@ -58,9 +74,9 @@ startService() {
stopService ${serverName}
if [ "$1"x != "stop"x ] ;then
sleep 1
startService ${serverName}
checkResult $?
sleep 1
startService ${serverName}
checkResult $?
else
echo "Service ${serverName} has stopped"
echo "Service ${serverName} has stopped"
fi