在后台启动一个进程,执行一个任务,然后在后台杀死进程

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

我有一个如下所示的脚本:

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

selenium 服务器需要 运行 才能进行测试,但是在 phpunit 命令完成后,我想终止 运行 的 selenium 服务器。

我该怎么做?

你大概可以把进程的PID保存在一个变量里,然后用kill命令杀掉它。

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

我自己没有测试过,我想写在评论上,但信誉还不够:)

执行脚本时,会创建一个新的 shell 实例。这意味着新脚本中的 jobs 不会在父脚本 shell 中列出任何作业 运行。

由于 selenium-server 服务器是在新脚本中创建的唯一后台进程,因此可以使用

将其终止
#The first job 
kill %1

或者

#The last job Same as the first one
kill %-

只要您不在后台启动任何其他进程(您确实没有),就可以使用 $!直接:

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