从 bash 脚本打开终端并检测它何时手动关闭

问题描述 投票:0回答:1

我写了这个简短的脚本来自动化 PCIe 卡测试:

#!/bin/bash
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
FIRST_DIR="$BASE_DIR"
SECOND_DIR="$BASE_DIR/dir1/"
THIRD_DIR="$BASE_DIR/dir2/"
gnome-terminal --working-directory="$FIRST_DIR" -- bash -c "
    echo 'lspci pcie cards';
    ./Delete_log_files.sh; 
    lspci -n; 
    ./Load_drivers.sh; 
    exec bash;"
sleep 1
gnome-terminal --working-directory="$SECOND_DIR" -- bash -c "
    echo 'run GDMS app'; 
    make; 
    sudo ./main;
    exec bash;"
sleep 1  # Wait for 1 seconds
gnome-terminal --working-directory="$THIRD_DIR" -- bash -c "
    echo 'run GDMS app';    
    make; 
    sudo ./main;
    exec bash;"

脚本按预期工作。它打开3个终端,并对终端SECOND_DIR和THIRD_DIR执行无限测试。执行测试直到用户使用 Ctrl+c 手动关闭这些终端。

我的下一个任务是在脚本中检测这两个终端何时关闭,并执行一些命令。

我尝试检测终端进程何时终止:

#!/bin/bash
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
FIRST_DIR="$BASE_DIR"
SECOND_DIR="$BASE_DIR/dir1/"
THIRD_DIR="$BASE_DIR/dir2/"
gnome-terminal --working-directory="$FIRST_DIR" -- bash -c "
    echo 'lspci pcie cards';
    ./Delete_log_files.sh; 
    lspci -n; 
    ./Load_drivers.sh; 
    exec bash;"
sleep 1
gnome-terminal --working-directory="$SECOND_DIR" -- bash -c "
    echo 'run GDMS app'; 
    make; 
    sudo ./main;
    exec bash;"   & SECOND_PID=$!
sleep 1  # Wait for 1 seconds
gnome-terminal --working-directory="$THIRD_DIR" -- bash -c "
    echo 'run GDMS app';    
    make; 
    sudo ./main;
    exec bash;"  & THIRD_PID=$!
    wait "$SECOND_PID" "$FIRST_PID"
    ./Delete_log.sh

此脚本在两个终端关闭之前执行Delete_log.sh,所以我想这不是正确的解决方案。

bash terminal pid
1个回答
0
投票

当spawn终端完成其任务时,它可以向根终端触发USR1信号。您需要做的是捕获来自根脚本的信号并完成内务工作。

#!/usr/bin/env bash

sigusr1_received=false

function catch_sigusr1() {
    sigusr1_received=true
    echo "OK"
}

trap catch_sigusr1 USR1

gnome-terminal -- bash -c "bash -ic 'source temp.bash' ; kill -USR1 $$"&

while ! $sigusr1_received ; do
    sleep 1
    echo -n .
done
echo
echo "SIGUSR1 received"
# do something after receiving SIGUSR1
© www.soinside.com 2019 - 2024. All rights reserved.