Bash

無法讓 bash 集群工作

  • March 13, 2018

我從我所看到的關於 bashflock函式的內容中派生了一個範例 bash 腳本。我願意:

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

然後我連續執行func&,每個都hello world立即列印,而我希望第一個列印消息,其餘的退出。我在這裡想念什麼?

考慮這個範例,基於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

引用自:https://unix.stackexchange.com/questions/429973