linux - 在 bash 中运行具有依赖性的并行函数

标签 linux bash

我有两个功能:

主要工作需要一些不一致的时间:

functionA {
        sleep 10  #FOR INSTANCE
    ((a++))  #added to try catching job finish
}

其他绘制进度:

functionB {
    # DOT PROGRESS COUNTER
}

我需要 functionB 仅在 functionA 处于事件状态时运行,所以我这样做:

a=0    
    until ((a>0))
        do
            functionA & functionB 
        done
    echo "functionA is done"

但是,结果我得到了两个函数的无限循环。

也尝试了 while 循环 - 结果是一样的。

functionA 完成时,应该如何停止 functionB

编辑:在调试器中,我看到 functionB"$a" 始终为 0。为什么?

最佳答案

如果我没有正确理解你的问题,我认为这可能会做到——

#!/bin/bash
done=

functionA() {
    sleep 3         # Placeholder for the actual work functionA does
    done=y          # Tell the outer loop we're done
    kill "$1"       # Stop the progress indicator
}

functionB() {
    while :; do     # The progress indicator - run forever
        echo .
        sleep 1
    done
}

until [[ "$done" ]]; do
    functionB &
    functionA $!
done

$!是最后生成的后台进程的 PID,在本例中是在后台运行 functionBbash 子外壳(一个单独的进程)。

我认为 functionB 总是将 $a 视为 0 因为 functionA 是在子 shell 中运行的,所以它对 a 的更改从未返回到运行 functionB 的主 shell。

相比之下,上面的代码在子 shell 中运行 functionB 并让 functionA 明确地从主 shell 中终止该子 shell。这样,functionAdone 的更改在 until 循环中可见(我认为)。

示例输出:

$ ./test.sh
.
.
.
$

另一种选择

如果 functionA 可能需要运行多次,你可以使用这个:

#!/bin/bash
done=

functionA() {
    sleep 3         # Do work
    done=y          # If functionA needs to run again, don't set $done
}

functionB() {
    while :; do     # Run forever, until terminated
        echo .
        sleep 1
    done
}

functionB &         # Start the progress indicator
progress_pid="$!"

until [[ "$done" ]]; do     # Do the work
    functionA
done

kill "$progress_pid"    # Stop the progress indicator

关于linux - 在 bash 中运行具有依赖性的并行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51948203/

相关文章:

linux - 无法在 Parrot Linux 上安装 strace

linux - 如何使用 monit 轮询多个 pid

linux - 如何在 Linux 上使用 exec 选项转义传递给 find 的命令

linux - 如何将当前路径复制到剪贴板?

git - 在文件中写入 git 分支

macos - Bash:在 OS X 下的字符串中查找字符的位置

java - 如何在Serenity bdd中手动使步骤失败而不跳过其他步骤

linux - 在Linux中使用已分配的内存,时间限制和权限运行文件/命令

windows - msys中的sudo相当于什么?

linux - 我在 bash 代码中使用 awk 语句时遇到一些困难