一个 shell 脚本 (.sh) 在后台调用另一个脚本调用的无限循环到 运行

A shell script (.sh) that calls an infinite loop called by another script to run in the background

本质上,我正在有限的指令集框架上运行(在嵌入式设备上 运行)。思路很简单。

我调用了一个生成两个文件的脚本:

文件A的内容:

#!/bin/sh
sh background_while&

文件 B 的内容:

#!/bin/sh

while true
do
 #some commands
 sleep 5
done

我想终止这个在后台调用的进程。有人可以展示如何使用键盘中断最好地完成这项工作吗?

如果scriptA 在后台调用scriptB 后才结束,那么您不能继续等待键盘中断。因此,不是立即结束 scriptA 你可以有一个紧密的循环并等待信号,然后使用 trap.

终止你的后台进程

类似于:

scriptA

#!/bin/bash

function kill_background(){
   kill ${myPid}
}

trap kill_background SIGINT

bash ./scriptB.sh &
myPid=$!

wait

您的脚本 B 将相同。 $! 获取最后执行的命令(您的 scriptB)的 pid,wait 使 scriptA 等待所有后台进程到 return。 trap 将捕获中断信号并终止您的脚本 B。