首页 > 解决方案 > 在后台启动服务器,运行代码并在单个脚本中再次停止服务器

问题描述

我想创建一个启动服务器的 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

这种脚本的正确(或更好)方法是什么?

标签: bash

解决方案


这是我根据 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

推荐阅读