Reputation: 1342
My goal is to run multiple processes using bash, then wait for user input (for instance, issuing a command of 'exit') and exiting out upon that command.
I have the bits and pieces, I think, but am having a hard time putting them together.
From what I saw, I can run multiple processes by pushing them to the back, like so:
./process1 &
./process2 &
I also saw that $! returns the most recently run process pid. Does this, then make sense:
./process1 &
pidA = $!
./process2 &
pidB = $!
From there, I am trying to do the following:
echo "command:"
read userInput
if["$userInput" == "exit"]; then
kill $pidA
kill $pidB
fi
does this make sense or am I not appearing to be getting it?
Upvotes: 0
Views: 42
Reputation: 1342
end code resulted in:
#!/bin/bash
pushd ${0%/*}
cd ../
mongoPort=12345
mongoPath="db/data"
echo "Starting mongo and node server"
db/bin/mongod --dbpath=$mongoPath --port=$mongoPort &
MONGOPID=$!
node server.js &
NODEPID=$!
while [ "$input" != "exit" ]; do
read input
if [ "$input" == "exit" ]; then
echo"exiting..."
kill $MONGOPID
kill $NODEPID
exit
fi
done
Upvotes: 0
Reputation: 5155
That looks good, although you'll probably need a loop on the user input part.
Note that you need to be careful with shell syntax. "pidA = $!" is not what you think; that's "pidA=$!". The former will try to run a program or command named pidA with arguments "=" and the PID of the last started background command.
Also note that you could use the "trap" command to issue the kill commands on termination of the shell script. Like this:
trap "kill $!" EXIT
Upvotes: 3