Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a process in background, do a task, then kill the process in the background

I have a script that looks like this:

pushd .
nohup java -jar test/selenium-server.jar > /dev/null 2>&1 &
cd web/code/protected/tests/
phpunit functional/
popd

The selenium servers needs to be running for the tests, however after the phpunit command finishes I'd like to kill the selenium-server that was running.

How can I do this?

like image 900
ComputerLocus Avatar asked May 11 '15 14:05

ComputerLocus


3 Answers

You can probably save the PID of the process in a variable, then use the kill command to kill it.

pushd .
nohup java -jar test/selenium-server.jar > /dev/null 2>&1 &
serverPID=$!
cd web/code/protected/tests/
phpunit functional/
kill $serverPID
popd

I haven't tested it myself, I'd like to write it on a comment, but not enough reputation yet :)

like image 198
zapatilla Avatar answered Nov 15 '22 20:11

zapatilla


As long as you don't launch any other process in the background - which you don't - you can use $! directly:

pushd .
nohup java -jar test/selenium-server.jar > /dev/null 2>&1 &
cd web/code/protected/tests/
phpunit functional/
kill $!
popd
like image 28
alindobre Avatar answered Nov 15 '22 20:11

alindobre


When the script is excecuted a new shell instance is created. Which means that the jobs in the new script would not list any jobs running in the parent shell.

Since the selenium-server server is the only background process that is created in the new script it can be killed using

#The first job 
kill %1

Or

#The last job Same as the first one
kill %-
like image 43
nu11p01n73R Avatar answered Nov 15 '22 20:11

nu11p01n73R