Mohamad Ibrahim
Mohamad Ibrahim

Reputation: 5575

Managing Shell Tasks

I am writing the following shell script:

perf stat taskset -c 0 runspec  & perf stat taskset -c 1 runspec 

perf stat taskset -c 0 runspec  & perf stat taskset -c 1 runspec 

As seen, each line consists of two tasks submitted to two different cpu's. I want a way to guarantee that the second line "the second two tasks" will not start executing until the first two tasks complete successfully. Is there away to do it?

Upvotes: 1

Views: 391

Answers (2)

tripleee
tripleee

Reputation: 189749

You need to wait for the PID of the background process.

perf stat taskset -c 0 runspec &
pid=$!
perf stat taskset -c 1 runspec 
wait $pid

perf stat taskset -c 0 runspec &
pid=$!
perf stat taskset -c 1 runspec
wait $pid

Clearly, this would be more elegant with a bit of additional refactoring. Perhaps like this:

parallel () {
    local pid
    # Danger: unquoted interpolation
    $1 &
    pid=$!
    # Danger: unquoted interpolation
    $2
    wait $pid
}

prun () {
    perf stat taskset -c $1 runspec
}

parallel "prun 0" "prun 1"
parallel "prun 0" "prun 1"

Notice that the parallel function interpolates $1 and $2 without double quotes. For this toy demonstration, that is harmless, but if you end up needing to pass in quoted strings as arguments, you will need a more elaborate solution.

Upvotes: 3

mjgpy3
mjgpy3

Reputation: 8947

Did you try running it without the '&' character? Usually the ampersand tells bash to run a command in the background and continue on to the next one. Without the ampersand the tasks should wait until completion to move on to the next one.

Michael G.

Upvotes: 0

Related Questions