LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash: run a script at most 3 times simultanously (https://www.linuxquestions.org/questions/programming-9/bash-run-a-script-at-most-3-times-simultanously-354470/)

paterijk 08-18-2005 02:56 AM

bash: run a script at most 3 times simultanously
 
Hi

I would like a script (let us call it simu) to run at most 3 times simultanously (to avoid overloading my server).

My idea would be to write a second script which would run simu only if less then 3 simus are already running. If 3 simus are running, he should wait for another one to finish, before starting a new one.

Does anyone know how I could do this?

Thank you for your help

Patrick

keefaz 08-18-2005 04:53 AM

Why not use a file to store a number and increment it following the number
of time you start your script ?

bigearsbilly 08-18-2005 05:38 AM

with xinetd you can sepcify how many servers to start.
dunno about inetd.

theYinYeti 08-18-2005 09:43 AM

The problem you'll have is synchronisation. The solution has to be via some atomic operation, like a mv or a ln for example...

Yves.

bulliver 08-18-2005 02:49 PM

At the top of your script you could put:
Code:

check_instances() {
NUM_INSTANCES=$(ps aux | grep simu | wc -l)
if [[ $NUM_INSTANCES -ge 4 ]]; then
        echo "3 simu instances already running..."
        sleep 5
        check_instances
fi
}

check_instances
# the rest of your code here...

Here we check if your script is found 4 times in the process table rather than three, because "ps aux | grep simu | wc -l" is counted itself there. As written this function will check every 5 seconds, but you can change that by modifying the "sleep" value. Once there are less than 3 instances running the rest of your script will run...

There is a possibility for false-positives here (if the string "simu" is found elswhere in your process table) but this will dissappear if you choose a more unique name for your script.


All times are GMT -5. The time now is 04:39 PM.