0

I tried to use asynchronous functionality in a bash script. It worked in a way. Here is the code.

echo "Process 1 lasts $1 seconds longer" && sleep $1 &
pid1=$!
echo "Process 2 lasts $2 seconds longer" && sleep $2 &
pid2=$!

wait $pid1
echo "Process 1 ended at $(date +%T) with exit status $? and pid $pid1"
wait $pid2
echo "Process 2 ended at $(date +%T) with exit status $? and pid $pid2"

But if I ran the script as ./script1.sh 8 2 , it doesn't print the completion of process2 after 2 seconds. After the completion of process 1, completion of both processes will be echoed out. Can someone show me what I am missing? I want it to echo the completion of a process at the moment it finished...

tad
  • 117
  • 7
  • The script simply runs from top to bottom. You will need something like a loop over the processes and check with `kill -0` when they die, then `wait` on the one which has died. Probably `sleep` between iterations to avoid spending all of your CPU on this. – tripleee May 19 '22 at 11:49
  • Sorry, I couldn't realize the similarity between my question and similar question. Can you shed more light on it please?? – tad May 19 '22 at 12:12
  • The answer https://stackoverflow.com/a/70670852/874188 has a section specifically about this, though you have to scroll down a bit. Their use of `pid` is not portable but seems equivalent to `kill -0` – tripleee May 19 '22 at 12:15
  • https://stackoverflow.com/a/69786242/874188 has a solution for Bash 5.1+ with `wait -p` – tripleee May 19 '22 at 12:17

0 Answers0