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

会有一股神秘感。 提交于 2019-12-21 11:30:05

问题


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


回答1:


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



回答2:


for instance in {1..40}
do
  php myscript &
done



回答3:


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



回答4:


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.




回答5:


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



回答6:


This script is a loop that creates instances of the 'while true; do :' loop. It continues making jobs until it's cancelled, and all of the jobs run in the background. You can add variables for index counter and change : to your code.

while true; do while true; do :; done & done

to stop:

killall bash



来源:https://stackoverflow.com/questions/2220030/how-to-make-a-bash-script-that-creates-40-simultaneous-instances-of-a-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!