无法让 bash 群开始工作

无法让 bash 群开始工作

我从我所看到的关于 bashflock函数的内容中得出了一个示例 bash 脚本。我愿意:

func()
{
    42>/home/foo
    flock -e 42 || exit 1
    echo "hello world"
    sleep 5
}

然后我连续运行func&,每个都hello world立即打印,而我希望第一个打印消息,其余的退出。我在这里缺少什么?

答案1

根据flock手册页中的示例考虑这个示例:

#!/bin/bash

func() {
    echo "$$ trying to acquire lock"
    (
        flock -e 42
        echo "lock acquired by $$"
        sleep 10
    ) 42> /tmp/mylock
    echo "lock released by $$"
}

func

现在,如果我运行该脚本一次:

$ bash ex.sh
22241 trying to acquire lock
lock acquired by 22241
lock released by 22241

如果我在此脚本的 10 秒睡眠窗口内运行两个实例(第一个在后台运行),可能的事件顺序是:

$ bash ex.sh& bash ex.sh
[1] 24518
24519 trying to acquire lock
24518 trying to acquire lock
lock acquired by 24519
lock released by 24519
lock acquired by 24518
$
lock released by 24518

在此示例中,第二个进程赢得了竞争并首先获取了锁。然后它释放锁并允许第一个(后台)进程获取锁,然后释放锁。

我可以在启动它们之间引入延迟来提高第一个进程赢得竞争的机会:

$ bash ex.sh& sleep 1; bash ex.sh
[1] 30158
30158 trying to acquire lock
lock acquired by 30158
30179 trying to acquire lock
lock released by 30158
lock acquired by 30179
lock released by 30179

相关内容