Search code examples
bashprocessjobspid

How to spawn n processes and start another after one finishes using bash?


I'm trying to write a script that will run n number of processes in parallel which are forked from the main script. The number of running processes should always be n, but the execution times per process may vary.

Example, I start three processes with pid's: 1, 2, and 3. When one of the three processes ends, I'd like to start a new process. If 2 finishes first, I'll spawn off process 4 so the running pid's will be: 1, 3, and 4.

I've viewed other questions where the wait command is used until all the jobs have finished. In my case I do not want to have to wait until every job is done to continue, just when one of the running jobs finishes.


Solution

  • wait -n `jobs -p`
    

    Seems to do the job. Thanks for the guidance l'L'l and hek2mgl.