-   Programming (
-   -   bash: run a script at most 3 times simultanously (

paterijk 08-18-2005 03:56 AM

bash: run a script at most 3 times simultanously

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


keefaz 08-18-2005 05: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 06:38 AM

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

theYinYeti 08-18-2005 10: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...


bulliver 08-18-2005 03:49 PM

At the top of your script you could put:

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

# 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 06:47 AM.