下一个进程完成时结束后台进程

Finish background process when next process is completed

大家好

我正在尝试从 Makefile 目标实施自动化测试 运行。由于我的测试依赖于 运行 docker 容器,我需要在整个测试执行期间检查容器是否已启动和 运行,如果它已关闭,则重新启动它。我正在尝试使用 bash 脚本,在后台模式下使用 运行。
乍一看,代码如下所示:

run-tests:
        ./check_container.sh & \
        docker-compose run --rm tests; \
        #Need to finish check_container.sh right here, after tests execution
        RESULT=$$?; \
        docker-compose logs test-container; \
        docker-compose kill; \
        docker-compose rm -fv; \
        exit $$RESULT

测试有不同的执行时间(从 20 分钟到 2 小时),所以我之前不知道需要多少时间。因此,我尝试在脚本中比最长的测试套件更长时间地轮询它。脚本看起来像:

#!/bin/bash

time=0

while [ $time -le 5000 ]; do
  num=$(docker ps | grep selenium--standalone-chrome -c)
  if [[ "$num" -eq 0 ]]; then
    echo 'selenium--standalone-chrome container is down!';
    echo 'try to recreate'
    docker-compose up -d selenium
  elif [[ "$num" -eq 1 ]]; then
    echo 'selenium--standalone-chrome container is up and running'
  else
    docker ps | grep selenium--standalone-chrome
    echo 'more than one selenium--standalone-chrome containers is up and running'
  fi
  time=$(($time + 1))
  sleep 30
done

所以,我正在寻找如何在测试 运行 完成后准确退出脚本,这意味着在命令 docker-compose run --rm tests 完成后?

P.S。也可以,如果后台进程可以在 Makefile 目标完成时完成

Docker(和 Compose)在退出时可以 restart containers automatically。如果您的 docker-compose.yml 文件有:

version: '3.8'
services:
  selenium:
    restart: unless-stopped

然后 Docker 将完成您的 shell 脚本所做的一切。如果它也有

services:
  tests:
    depends_on:
      - selenium

那么 docker-compose run tests 行也会导致 selenium 容器启动,你根本不需要脚本来启动它。

当您在后台启动命令时,special parameter $! 包含其进程 ID。您可以将其保存在一个变量中,然后 kill(1) 它。

在简单的 shell-script 语法中,没有 Make-related 转义:

./check_container.sh &
CHECK_CONTAINER_PID=$!

docker-compose run --rm tests
RESULT=$?

kill "$CHECK_CONTAINER_PID"