Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

linux - Threads in bash?

Is it possible to use threads in bash scripts. I have a driver class in java that i'm trying to run multiple instances of at the same time. The only way i know to do this is make threads in bash, but i'm not sure if thats even possible. Any help would be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Bash doesn't support threading per se, but you could launch multiple java processes in the background, like:

java myprog &
java myprog &
java myprog &

Anything more than that you might look into Python or Ruby, which have thread management utilities, you could wait for each one to finish and collect output/exit status, etc.

Edit: Borrowing the suggestion from @CédricJulien to use wait, here's a more thorough example. Given this MyProg.java program:

public class MyProg {
    public static void main(String[] args) {
        System.exit(Integer.parseInt(args[0]));
    }
}

you could write the following bash-threads.sh script to launch multiple instances of it in parallel:

#!/bin/bash
set -o errexit

java MyProg 1 &
pid1=$!
java MyProg 0 &
pid2=$!
java MyProg 2 &
pid3=$!

wait $pid1 && echo "pid1 exited normally" || echo "pid1 exited abnormally with status $?"
wait $pid2 && echo "pid2 exited normally" || echo "pid2 exited abnormally with status $?"
wait $pid3 && echo "pid3 exited normally" || echo "pid3 exited abnormally with status $?"

Its output is:

pid1 exited abnormally with status 1
pid2 exited normally
pid3 exited abnormally with status 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...