Last Updated: February 25, 2016
·
1.798K
· newsociallife

Only single instance

Want that a process runs forever and only a single time?
Just use my simple bash script and enjoy :)

#!/bin/bash
while [ 1 ];  do
    pcount=`ps -ef | grep NAME_OF_YOUR_PROCESS | awk '{print $2}' | wc -l`
    if [ "$pcount" != "2" ]; then
        echo "Killing all NAME_OF_YOUR_PROCESS processes"
        ps -ef | grep NAME_OF_YOUR_PROCESS | awk '{print $2}' | xargs kill -9
        COMMAND_TO_START_YOUR_PROCESS &
    fi;
    sleep 1;
done;

of course you have to replace

NAME_OF_YOUR_PROCESS

with the name of the process witch can have only one instance ( the name shown in ps -ef or ps-aux )

and

COMMAND_TO_START_YOUR_PROCESS

with the command with whom you start your process

are you asking worself why I wrote:

if [ "$pcount" != "2" ]; then

grep => 1 process
yourprocess => 1 process
your
processsecondinstance => 1 process and so on...

so if you have two process you will have grep and your process so it's all right....
if you have one instance you have only grep... so you have to start your process again
if you have more than two instances you have grep and your process started more than one time, so you have to kill all instances of your process and then restart it so that you will have only one instance...

you have to run my shell script with:

filename &

where filename is the name with whom you saved the file

example for noip

#!/bin/bash
while [ 1 ];  do
        no_ip_cnt=`ps -ef | grep noip2-i686 | awk '{print $2}' | wc -l`
        if [ "$no_ip_cnt" != "2" ]; then
                echo "Killing all noip processes"
                ps -ef | grep noip2-i686 | awk '{print $2}' | xargs kill -9
                /path/to/noip/noip-i686 &
        fi;
        sleep 1;
done;