2

I'm trying to run a command in parallel by detaching it:

sleep 2s &

#!/bin/bash
for ((i=1;i<=3;i++)); do
    sleep 2s &
    pids[${i}]=$!
done

for pid in ${pids[*]}; do
    wait $pid
done

Which will spawn 3x the command 'sleep 2s' and wait for the commands to be finished

This is executed as expected (2 seconds):

pi@raspberrypi:~/scripts $ time ./test.sh

real 0m2.029s user 0m0.022s sys 0m0.052s

When I try to capture the output of the process, the execution changes from parallel to sequential. The execution time is now 6 seconds (3x 2 seconds)

output[${i}]=$(sleep 2s &)

#!/bin/bash
for ((i=1;i<=3;i++)); do
    output[${i}]=$(sleep 2s &)
    pids[${i}]=$!
done

for pid in ${pids[*]}; do
    wait $pid
done

pi@raspberrypi:~/scripts $ time ./test.sh

real 0m6.030s user 0m0.006s sys 0m0.015s

Any ideas on how to capture the output whilst running the commands in parallel? Thanks!

Jon V
  • 506
  • 1
  • 3
  • 21
  • What output are you trying to capture out of `sleep 2`, do you have some other command to run? – Inian Jan 17 '19 at 08:48
  • 2
    How could the variable possibly obtain a value before the process whose output you are capturing has finished? – tripleee Jan 17 '19 at 08:49
  • @Inian I used sleep as an example, the actual command is to program a PIC chip via pickle (http://hg.kewl.org/pub/pickle), but I think it is irrelevant to my question ;) – Jon V Jan 17 '19 at 08:50
  • 1
    @JonathanV: Using command-substitution(`$(..)`) won't work for your case. So your problem is try to capture output of a command running in background right? – Inian Jan 17 '19 at 08:54
  • @Inian, yes exactly. writing to a file would be an option, but i prefer an option that does not leave traces after the execution (like a variable) – Jon V Jan 17 '19 at 08:59
  • 1
    @JonathanV: Would answers in this question help you - https://stackoverflow.com/q/20017805/5291015. If so I'm closing this as a duplicate – Inian Jan 17 '19 at 09:08

0 Answers0