Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash linux: start multiple program in parallel and stop all when one has finished

Tags:

linux

bash

I'm working on Ubuntu and I want to create a bash file that do these things:
Launch one program (prog0) on core 1.
Wait 3 seconds.
Then log the information of CPU and Memory usage for prog0 (I use two instances of pidstat on core 0 for logging that information).
Then start another program (prog1) on core 0.
When prog1 has finished (I think that prog1 exits automatically), I would like to exit from all the previous process (prog0 and two pidstat).

taskset -c 1 prog0 -option0 &
sleep 3
taskset -c 0 pidstat 1 -C prog0 -u > log2 &
taskset -c 0 pidstat 1 -C prog0 -r > log3 &
taskset -c 0 prog1 -option1 > log1 

I don't know how to exit or kill all the processes started when prog1 has finished.

like image 450
user1382278 Avatar asked Feb 28 '13 15:02

user1382278


People also ask

How do I run multiple scripts in bash?

The Operators &&, ||, and ; The first logical operator we will be looking at will be the AND operator: &&. In Bash, it is used to chain commands together. It can also be used to run two different scripts together.

Do bash scripts run in parallel?

To run script in parallel in bash, you must send individual scripts to background. So the loop will not wait for the last process to exit and will immediately process all the scripts.


1 Answers

Add:

trap 'kill $(jobs -p)' EXIT

to the beginning of your script. This will kill all background jobs when your script exits.


To create a script open a new file and paste the following into it:

#!/bin/bash
trap 'kill $(jobs -p)' EXIT
taskset -c 1 prog0 -option0 &
sleep 3
taskset -c 0 pidstat 1 -C prog0 -u > log2 &
taskset -c 0 pidstat 1 -C prog0 -r > log3 &
taskset -c 0 prog1 -option1 > log1

Save the file as runme.sh.

Make it executable: chmod +x runme.sh

Run it by executing: ./runme.sh or to run it in the background: ./runme.sh &

Now, when the last command taskset -c 0 prog1 -option1 > log1 has finished, the script will exit and it will kill all the background processes that it started.

like image 168
dogbane Avatar answered Sep 28 '22 15:09

dogbane