Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a bash script that creates 40 simultaneous instances of a program?

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!!

like image 584
chris Avatar asked Feb 08 '10 06:02

chris


People also ask

How do you run a shell script multiple times in parallel?

Running Commands in Parallel using Bash Shell I basically need to execute 3 wget commands and make them run in parallel. The best method is to put all the wget commands in one script, and execute the script. The only thing to note here is to put all these wget commands in background (shell background).

How do I run the same script multiple times in Linux?

Repeating a Command Using 'for' Loop You can use a 'for' loop to print a certain command multiple times. There are different variations of the 'for' loop, and we will explore all of them with the help of different bash scripts.

How do you run multiple scripts one after another but only after previous one got completed?

Using wait. We can launch a script in the background initially and later wait for it to finish before executing another script using the wait command. This command works even if the process exits with a non-zero failure code.


4 Answers

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
like image 123
sth Avatar answered Nov 04 '22 16:11

sth


for instance in {1..40}
do
  php myscript &
done
like image 20
ghostdog74 Avatar answered Nov 04 '22 15:11

ghostdog74


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
like image 32
codaddict Avatar answered Nov 04 '22 14:11

codaddict


if you have the seq(1) program (there are chances that 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.

like image 32
Tjunier Avatar answered Nov 04 '22 14:11

Tjunier