bash - 在后台启动服务器,运行代码并在单个脚本中再次停止服务器
问题描述
我想创建一个启动服务器的 bash 脚本,等待服务器启动,然后运行一些代码(我们由服务器处理),最后再次停止服务器。
这是我所拥有的,并附有关于它为什么不起作用的评论:
#!/bin/bash
# Expected: Start the local selenium server and push it to the background.
# Actual: Script continues instantly without waiting for the server to start!
selenium-server -port 4444 &
# Expected: Run the tests, which require the local selenium server to be started
# Actual: Tests fail because the server is not ready.
phpunit tests/ui-tests.php
# Expected: Exiting the process also stops the background job (server).
# Actual: The server continues running interactively in the terminal until stopped via Ctrl-C.
exit
这种脚本的正确(或更好)方法是什么?
解决方案
这是我根据 markp-fuso 的反馈构建的工作脚本:
#!/bin/bash
start_server() {
echo "Start server ..."
selenium-server -port 4444 &
server_pid=$!
# Wait for the server to start (max 10 seconds)
for attempt in {1..10}; do
my_pid=$(lsof -t -i tcp:4444)
if [[ -n $my_pid ]]; then
# Make sure the running server is the one we just started.
if [[ $my_pid -ne $server_pid ]]; then
echo "ERROR: Multiple Selenium Servers running."
echo "→ lsof -t -i tcp:4444 | xargs kill"
exit 1
fi
break
fi
sleep 1
done
if [[ -z $my_pid ]]; then
echo "ERROR: Timeout while waiting for Selenium Server"
exit 1
fi
}
stop_server() {
echo "Stop Server ..."
kill $server_pid
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
start_server
phpunit tests/ui-tests.php
stop_server
推荐阅读
- haskell - 更新状态单子时模式匹配是冗余的
- logging - GCP 项目内部错误检索日志
- c# - 在 RazorPages asp.net core 2_1 中显示 parentcategoryname
- php - MySQL查询检查常用时间间隔并显示间隔
- javascript - Mongoose:当使用“toObject”时,res.json 返回带有空记录的数组。为什么以及如何解决这个问题?
- java - Java 中的连接重置但使用 Postman
- javascript - 异步函数进行的重复调用
- arrays - 我想在 void 函数的结构数组中添加信息,但我认为我没有正确使用指针
- c++ - 我的朋友如何在不提供路径的情况下拥有文件?
- python - 计算具有特定条件的矩阵