views:

199

answers:

5

I am new to bash and Linux. I have a program I have written that I want to create multiple simultaneous instances of.

Right now, I do this by opening up 10 new terminals, and then running the program 10 times (the command I run is php /home/calculatedata.php

What is the simplest way to do this using a bash script? Also, I need to know how to kill the instances because they are running an infinite loop.

Thanks!!

+3  A: 

You can use a loop and start the processes in the background with &:

for (( i=0; i<40; i++ )); do
   php /home/calculatedata.php &
done

If these processes are the only instances of Php you have running and you want to kill them all, the easiest way is killall:

killall php
sth
so in this case, the program is "php"?
chris
@chris: yes, it would be php with the script name as parameter. (I updated he answer)
sth
thanks for the help!
chris
+3  A: 

How about running the php process in the background:

#!/bin/bash
for ((i=1;i<=40;i+=1)); do
  php /home/calculatedata.php &
done

You can terminate all the instances of these background running PHP process by issuing:

killall php

Make sure you don't have any other php processes running, as they too will be killed. If you have many other PHP processes, then you do something like:

ps -ef | grep /home/calculatedata.php | cut_the_pid | kill -9
codaddict
+1  A: 

You can start the instances with a simple loop and a terminating "&" to run each job in the background:

INSTANCES=40
for ((i=0; $i<$INSTANCES; ++i))
do
    mycmd &
done
Andrew Medico
thanks, is there a simple way to terminate the script's instances all at once?
chris
+2  A: 
for instance in {1..40}
do
  php myscript &
done
ghostdog74
+1 for using brace expansion
ammoQ
A: 

if you have the seq(1) program (chances are you have it), you can do it in a slightly more readable way, like this:

for n in $(seq 40); do
   mycmd &
done

In this case the n variable isn't used. Hope this helps

T

Tjunier
you can use brace expansion to simulate seq. {1..40}
ghostdog74
When I said "more readable" I meant more readable than the C-like for loops. The form with {1..40} is at least as readable, of course.
Tjunier