Reputation: 5287
I have a shell script which I need to start frequently. I can set the shortcut to start (which I use to start) but not to terminate. I need to Ctrl+C to terminate it. Resultantly sometimes end up opening many processes.
So what I want to do is to add some command in the script which checks if older process from the script exists and kill it then start the new one.
Just to make my requirement more clear, I tried following
Say the running script is /home/user/runscript.sh
.
ps aux | grep runscript.sh
gives me
user+ 6135 0.0 0.0 16620 1492 ? S 18:28 0:00 /home/user/runscript.sh
user+ 6208 0.0 0.0 15936 952 pts/6 R+ 18:28 0:00 grep --color=auto runscript.sh
I prepended following in script
pkill -f runscript.sh
to kill the process if it is already running. It solved the purpose of killing the older process but didn't let new one start. The reason was obvious which I understood later.
What is the correct way to do this?
Upvotes: 1
Views: 1683
Reputation: 41958
You could just use killall
instead. The trouble is that you want to avoid killing your current process, but that's easily done with the -o
flag:
-o, --older-than
Match only processes that are older (started before) the time specified. The time is specified as a float then a unit. The units are s,m,h,d,w,M,y for seconds, minutes, hours, days, weeks, Months and years respectively.
Therefore this ought to work:
killall -o 5s runscript.sh
The other answer is fundamentally better as it's the resilient 'professional' approach, but this approach should work if it's just for your own script and you want to take the easy way out.
Upvotes: 2
Reputation: 42915
The typical approach to this is to use a file system based locking strategy:
The script creates a lock file (/var/lock/subsystem/...
) with its own process number as content. When being started, it first checks if such file already exists. If not, all fine. But if so, then it reads the process number from the file and uses it to check the process table. If such process still exists, then it can either exit (usual behavior), or it can terminate that process (what you ask for) by sending a SIG-TERM signal.
Upvotes: 7