Using shell scripting to start multiple background processes

I made yesterday some tests on a Java server running on a linux machine. So I had to run the Java server and a policy server in background, then I had to stop them to change some things and then I then I started them again several times ( I will explain in my next article why  I needed a policy server ) .  Of course, after I repeated this operation many times, I got bored and I decided to simplify my work by creating a shell script  and after some googling I found a way to run multiple background processes from a shell script.

#!/bin/bash
if [ $# -ne 1 ]; then
echo "Please select a command."
else
 case "$1" in
        start)
        echo "Starting chat servers..."
        { java -jar policyserver.jar 843 >/dev/null 2>&1 </dev/null & } &
        for ((  i = 7500 ;  i <= 7515;  i++  ))
        do
        echo "Starting server on port $i"
        { java -jar server.jar $i >/dev/null 2>&1 </dev/null & } &
        done
        ;;
        killall)
                kill -9 `ps -A | grep "java" | awk '{print $1}'`
        ;;
        *)
                echo "$1 command is not available"
        ;;
 esac
fi

Note. Don’t let many processes to hang in background because at some time your linux server will refuse to create more threads. Because you put the processes in background using this command { java -jar server.jar $i >/dev/null 2>&1 </dev/null & } & your console isn’t the parent process anymore, so if you close your console the processes will continue to run.

This entry was posted in Shell scripting and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *