Question:
bash question
I want to launch several instances of the application(s) in parallel from a bash script. Something like synchronization is needed.
I start with & . In this case, it turns out that the launching script does not know about the distance. "fate" of the running process. For example, I would like to use:
-
Expectation. After launching all the necessary (parallelly running) applications, the script that launched them waited until all of them were completed and / or some. of them. Upon completion, for example, the script might display messages indicating that the operation is complete.
-
Interrupt. If many processes are launched from the script, it is inconvenient to force them to end through the process manager (in the case when you get tired of waiting). If the child process were launched sequentially (without &), then by closing the console window from which the script was launched, all processes generated by it would also be terminated (forcibly). I would like to get something like that for parallel (through &) running processes. For example, the script asks, "should I terminate child processes?", I enter smth. in the console and all parallel running processes are forcibly terminated.
QUESTION: how can this be done in bash in a normal way (without the invention of bicycles), and in general, is it possible?
As requested by @alexander-barakin – non-working wait:
File: inv_3.BASh
#!/bin/bash
declare Path="$(dirname "${0}")"; Path="${Path%/}/";
declare Data="${Path}t2.data.fifo";
declare Can_write="${Path}t2.can.fifo";
trap "echo _ > \"${Can_write}\"; " Usr1;
aValue=$BASHPID;
bash "${Path}sub_3.BASh" $aValue &
wait;
echo ;
echo " JOBS:";
jobs -pr;
echo ;
echo "Завершено."
File: sub_3.BASh
#!/bin/bash
declare theRecievers="${1}";
declare Path="$(dirname "${0}")"; Path="${Path%/}/";
declare Data="${Path}t2.data.fifo";
declare Can_write="${Path}t2.can.fifo";
trap "echo $BASHPID: END" Exit;
kill -s Usr1 ${theRecievers};
i=2;
while ((i--)); do
while ! read < "${Can_write}"; do
kill -s Usr1 ${theRecievers};
done;
done;
Playback:
- Create files inv_3.BASh, sub_3.BASh
- Create a pipe in the same directory: t2.can.fifo, t2.data.fifo
- In console:
bash "inv_3.BASh"; echo $?;
Expected (from wait) behavior:
A script that calls wait does not execute the commands after the wait until child completes. the process, i.e., the output "… JOBS: …" should not be at all until the completion of the daughter. process.
I see:
JOBS:
14066
- I open the process manager: there is a process with pid 14066. The value of pid, of course, is different every time.
Answer:
-
waiting for all child processes to terminate is done using the
wait
command. -
intercepting the
sigint
signal (which is passed to the process when pressing ctrl + c ) and terminating all child processes is well described, for examplehere .