52coder
52coder

Reputation: 181

shell parallel programing with error control

Here is my code (learn form the book Linux shell scripting cookbook)

#/bin/bash

PIDARRAY=()

(echo aaa >> /dev/null;sleep 8; exit 0)&
PIDARRAY+=("$!")
(echo bbb >> /dev/null;sleep 4;echo helloworld; exit 1)&
PIDARRAY+=("$!")
(echo ccc >> /dev/null;sleep 16; exit 0)&
PIDARRAY+=("$!")


wait ${PIDARRAY[@]}

$! save the last bg task pid,so the PIDARRAY will save three bg task pid,I try to achive this:one task failed,kill the other two and exit the shell,but failed ,Here is my modify code:

#/bin/bash

PIDARRAY=()

(echo aaa >> /dev/null;sleep 100; exit 0)&
PIDARRAY+=("$!")
(echo bbb >> /dev/null;sleep 4;echo helloworld; exit 1)&
PIDARRAY+=("$!")
(echo ccc >> /dev/null;sleep 100; exit 0)&
PIDARRAY+=("$!")

wait ${PIDARRAY[@]}

if [ $? -ne 0 ]; then
    kill -9 PIDARRAY[0]
    kill -9 PIDARRAY[1]
    kill -9 PIDARRAY[2]
fi

there is one obvious error,if one task failed ,we need only kill another two task,not three,I put the if statement before and after wait,got not what I want,How can I achive my goal:one task failed,kill the other two and exit the shell

Upvotes: 1

Views: 132

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207650

I would use GNU Parallel for efficiently managing parallel tasks. So, in your case:

parallel --halt now,fail=1 ::: task1 task2 task3

There are a million ways to submit jobs, so you could store your job-list in a file called jobs:

echo aaa >> /dev/null;sleep 100; exit 0
echo bbb >> /dev/null;sleep 4;   echo helloworld; exit 1
echo ccc >> /dev/null;sleep 100; exit 0

and then run like this:

parallel --halt now,fail=1 < jobs

Output

helloworld
parallel: This job failed:
echo bbb >> /dev/null;sleep 4;   echo helloworld; exit 1

Upvotes: 1

Related Questions