Killing previous instances at first time,if running

老子叫甜甜 提交于 2019-12-04 06:24:20

问题


Following is my script 'Infinite.sh' code, I am running this script in background,Before running this script, i want to kill all previous instances. But this is killing my curent instance also.

kill -9 `ps ux|grep Infinite.sh|awk -F\  '{print $2}'`
while true;
do
echo -n "SLEEPING FOR 5 SECOND"
date
sleep 5
done

回答1:


Just eliminate the current process' PID from the list. To do this making just the minimal change to your code:

kill -9 `ps ux | grep Infinite.sh | awk -F\  -v pid=$$ 'pid != $2 {print $2}'`

The option -v pid=$$ sets the awk variable pid to the value of the current process' process ID. The expression pid != $2 {print $2} will print a process ID only if it differs from the current process' process ID.

To simplify the code, we could use pgrep:

kill -9 $(pgrep Infinite.sh | grep -v $$)

As triplee points out in the comments, kill -9 should only be used as a last resort. -9 (SIGKILL) prevents a process from cleaning up after itself, deleting temporary files, etc. Other signals that one may want to try first include -2 (SIGINT), -6 (SIGABRT), or -15 (SIGTERM, which is the default). As for which signals to use, Randal L. Schwartz recommends:

Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!

For more details on why kill -9 should be avoided, see here. For more information on the various Unix signals and their meaning, see wikipedia




回答2:


Anything can be dangerous. The better solution is to save your PID to a file everytime you run an instance. If a PID file exists and if the PID in that file is a valid and is an active process, kill that process. Save the PID of the current process after.

PID_FILE=/var/run/infinite.pid

# Read saved PID of previous instance.
read PID < "$PID_FILE"

# You may consider other safer signals like TERM, HUP, QUIT, and ABRT.
# Checking may also be optional. You can just send the signal right away.
kill -s 0 "$PID" &>/dev/null && kill -s 9 "$PID" &>/dev/null 

# Optionally wait for process to exit.
sleep 2s

# Optionally check it again.
kill -s 0 "$PID" &>/dev/null && { echo "Unable to kill process $PID."; exit; }

# Save PID.
echo "$$" > "$PID_FILE"



回答3:


Simply check if the pid is the same as the one of the running script.

Something like this could work:

#!/bin/bash

pids=($(pgrep "$(basename "$0")"))

for i in "${pids[@]}"
do
    (( $$ != i)) && kill "$i"
done

while :; do sleep 1;done
~                        


来源:https://stackoverflow.com/questions/24902611/killing-previous-instances-at-first-time-if-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!