linux - 在 Linux shell 上终止另一个函数内的函数

标签 linux bash shell

我对 shell 脚本非常陌生,我正在尝试找出如何终止在另一个函数内使用无限循环的函数。 代码或多或少看起来像这样:

finish=1

function1() {
    function2&
    ...
    finish=0
}
function2() {
    while [ $finish==1 ] 
    do
    ...
    done
}

脚本的主要部分仅调用函数1。当 function1 完成时,还有其他方法可以终止 function2 吗?我也尝试通过 id 杀死它,但无法使其工作。

最佳答案

bash 中的函数调用将在子 shell 中执行。您可以存储该子 shell 的 pid 并在 function1 退出之前杀死它。像这样:

function1() {
    function2&
    pid=$!

    ...

    kill "$pid"
}

function2() {
    while true 
    do
        ...
    done
}

关于linux - 在 Linux shell 上终止另一个函数内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597244/

相关文章:

linux - https ://example. com打开一个BIN文件供下载而不是页面内容

linux - 服务器上没有事件,每 5 秒记录一次

linux - 如何在 linux 中合并相似的行

mysql - 在 Monit 中使用 --login-path 检查脚本给出错误 1045 (28000)

linux - bash 脚本正确解释 awk

bash - 在 bash 中进行 float 学运算时为 "Invalid Arithmetic Operator"

linux - 通过 sendto() 的 UDP 广播返回 "Can' t assign requested address"on OS/X but not Linux

PHP set_include_path 配置

c++ - 在VS2019 C++跨平台程序中包含nuget包

python - linux - 导出带有文件链接的树目录列表